<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

// Check to ensure this file is included in Joomla!
defined ( '_JEXEC' ) or die ( 'Restricted access' );
$GLOBALS ['jbconfig'] = array ();
$GLOBALS ['JBVERSION'] = '1.5.0';
$GLOBALS ['JBPRODUCTKEY'] = 'COM_JAJOBBOARD';

require_once( dirname(__FILE__).DS."japermission.php" );

/**
 * Enter description here...
 *
 */
function component_configs() {
	global $mainframe;
	
	if ((defined ( 'JA-ADMINISTRATOR' ) || substr ( JPATH_BASE, - 13 ) == 'administrator') && ! isset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'JAJOBBOARD_CHECKED' )] )) {
		//check_license_time ();
		if( function_exists("date_default_timezone_set") && function_exists("date_default_timezone_get") )
			@date_default_timezone_set(@date_default_timezone_get());
	}
	
	if (defined ( 'COMPOENT_JAJOBS_CONFIG' )) {
		return;
	}
	
	global $jbconfig;
	
	$setup = new stdClass ( );
	$db = JFactory::getDBO ();
	$setup = new stdClass ( );
	$q = 'SELECT tab, data FROM #__ja_config';
	$db->setQuery ( $q );
	$rows = $db->loadObjectList ();
	if ($rows) {
		foreach ( $rows as $row ) {
			$jbconfig [$row->tab] = new JParameter ( $row->data );
		}
	}
	
	define ( 'COMPOENT_JAJOBS_CONFIG', true );
}

/**
 * Enter description here...
 *
 * @param unknown_type $item
 * @param unknown_type $fieldList
 * @param unknown_type $form
 * @return unknown
 */
function findFirstField($item, $fieldList, $form = 'view') {
	for($i = 0, $n = count ( $fieldList ); $i < $n; $i ++) {
		switch ($form) {
			case 'view' :
				if (($fieldList [$i]->display != 'hide_all') && ($fieldList [$i]->display != 'admin_only'))
					return $i;
			case 'edit' :
				if (($fieldList [$i]->display == 'hide_on_new') || ($fieldList [$i]->display == 'show_all'))
					return $i;
			case 'new' :
				if (($fieldList [$i]->display == 'hide_on_edit') || ($fieldList [$i]->display == 'show_all'))
					return $i;
		}
	}
}

/**
 * Enter description here...
 *
 * @param unknown_type $item
 * @param unknown_type $fieldList
 * @param unknown_type $form
 * @return unknown
 */
function findLastField($item, $fieldList, $form = 'view') {
	$n = count ( $fieldList );
	for($i = $n - 1; $i >= 0; $i --) {
		//		$input = rendfield($item, $fieldList[$i], false, true, true);
		switch ($form) {
			case 'view' :
				if (($fieldList [$i]->display != 'hide_all') && ($fieldList [$i]->display != 'admin_only'))
					return $i;
			case 'edit' :
				if (($fieldList [$i]->display == 'hide_on_new') || ($fieldList [$i]->display == 'show_all'))
					return $i;
			case 'new' :
				if (($fieldList [$i]->display == 'hide_on_edit') || ($fieldList [$i]->display == 'show_all'))
					return $i;
		}
	
	}
}

/**
 * Enter description here...
 *
 * @param unknown_type $usertype
 * @param unknown_type $user_id
 */
function prepare_data($usertype, $user_id = 0) {
	global $jbconfig;
	
	if ($user_id != 0)
		$user = JFactory::getUser ( $user_id );
	else
		$user = JFactory::getUser ();
	
	/*Update account user*/
	$jconfig = new JConfig();
	$timezone = JRequest::getVar('timezone', $jconfig->offset);
	$user->setParam('timezone', $timezone);
	$user->setParam('usertype', $usertype);
	if (! $user->save ()) {
		JError::raiseWarning('', JText::_( $user->getError()));
		return false;
	} 
	
	// Prepare data for employer - Begin -
	JRequest::setVar ( 'premium_posts_balance', $jbconfig ['account']->get ( 'begin_premium_posts' ) );
	JRequest::setVar ( 'standard_posts_balance', $jbconfig ['account']->get ( 'begin_standard_posts' ) );
	JRequest::setVar ( 'credit_balance', $jbconfig ['account']->get ( 'begin_credit_posts' ) );
	JRequest::setVar ( 'membership_active', 0 );
	//Prepare data for employer - End -	
	
	//Prepare data for transaction - Begin -
	if ($usertype == 'Job Seeker User')
		$subs_type = 'jobseeker';
	else
		$subs_type = 'employer';
	
	$db = JFactory::getDBO ();
	$query = 'SELECT * FROM #__ja_transactions ORDER BY id DESC';
	$db->setQuery ( $query );
	$max_invoice_id = $db->loadObjectList ();
	$max_invoice_id = $max_invoice_id ['0']->id;
	if (! $max_invoice_id)
		$max_invoice_id = $jbconfig ['billing']->get ( 'invoice_id_start' );
	$max_invoice_id = $max_invoice_id + 1;
	$paysys = get_payment_gateways ();
	$arr_subtype = JobBoardConstant::getSub_Type ();
	
	// Check register payment or not
	if( $subs_type == "employer" )
		$mustPay = $jbconfig['billing']->get("employer_membership_enabled", 0);
	else $mustPay = $jbconfig['billing']->get("candidate_membership_enabled", 0);
	
	if( ! $mustPay ){
		$query = 'SELECT * FROM #__ja_subscriptions WHERE subs_type="' . $subs_type . '" and isdefault=1';
		$db->setQuery ( $query );
		$subscriptions = $db->loadObjectList ();
	} else {
		$subID = JRequest::getVar("subscriptions_package", 0);
		if($subID == 0)
			$subID = JRequest::getVar("subscriptions_package_".$subs_type, 0);
		$query = 'SELECT * FROM #__ja_subscriptions WHERE id = '.$subID;
		$db->setQuery ( $query );
		$subscriptions = $db->loadObjectList ();
	}
	$arr_invoice_data = array ();
	$arr_invoice_data ['product_id'] 	= $subscriptions [0]->id;
	$arr_invoice_data ['product_type'] 	= 'S';
	$arr_invoice_data ['created_date'] 	= date ( 'Y-m-d H:i:s' );
	
	if( intval($subscriptions [0]->price) > 0 && $mustPay ){
		$arr_invoice_data ['completed'] 	= 0;
		JRequest::setVar ( 'membership_active', 0);
	}else $arr_invoice_data ['completed'] 	= 1;
	
	$arr_invoice_data ['user_id'] 		= $user->id;
	$arr_invoice_data ['value'] 		= $subscriptions [0]->qty;
	$arr_invoice_data ['amount'] 		= $subscriptions [0]->price;
	$arr_invoice_data ['payment_method'] = $jbconfig ['payment']->get ( 'ja_default_pay_meth' );
	$arr_invoice_data ['currency'] 		= $jbconfig['currency']->get('currency', '$');;
	JRequest::setVar ( 'arr_invoice_data', $arr_invoice_data );
	
	// Need approve?
	if( empty($subscriptions [0]->require_approved) ){
		if( $subs_type == "employer" )
			JRequest::setVar("require_approved", $jbconfig ['account']->get ( 'em_needs_approved', 0 ));
		else
			JRequest::setVar("require_approved", $jbconfig ['account']->get ( 'ca_needs_approved', 0 ));
	}else 
		JRequest::setVar("require_approved", $subscriptions [0]->require_approved);
	
	return ( ! $arr_invoice_data ['completed'] );
}

/**
 * Enter description here...
 *
 * @param unknown_type $user_id
 */
function initial_employer($user_id = 0) {
	if (! $user_id) {
		$user = JFactory::getUser ();
		$user_id = $user->id;
	}
	global $jbconfig;
	//		Change user's type - PhuongLH - begin		    
	//	    if ((getCurrentUserType()=='Guest')&&($user->usertype!='Administrator')&&($user->usertype!='Super Administrator'))
	//	    {
	if ($jbconfig ['account']->get ( 'em_needs_approved' ) == 0)
		updateUserType ( JBEMPLOYER_USER, $user_id );
	require_once (JPATH_COMPONENT_SITE . DS . 'models' . DS . 'jaemployers.php');
	require_once (JPATH_COMPONENT_SITE . DS . 'models' . DS . 'jatransactions.php');
	require_once (JPATH_COMPONENT_SITE . DS . 'models' . DS . 'japermissions.php');
	$transaction_model = new JobBoardModeljaTransactions ( );
	$permission_model = new JobBoardModelJAPermissions ( );
	$employer_model = new JobBoardModelJAEmployers ( );
	$transaction_model->store ( $user_id );
	$temp_employer = getItemByFieldName ( 'ja_employers', 'user_id', $user_id );
	if ($temp_employer) {
		JRequest::setVar ( 'cid', $temp_employer [0]->id );
		JRequest::setVar ( 'id', $temp_employer [0]->id );
	}
	$employer_model->store ();
	$permission_model->initial_per ( $user_id, 'Employer User' );
}

/**
 * Enter description here...
 *
 * @param unknown_type $user_id
 */
function initial_jobseeker($user_id = 0) {
	global $jbconfig;
	if ($user_id != 0)
		$user = JFactory::getUser ( $user_id );
	else {
		$user = JFactory::getUser ();
		$user_id = $user->id;
	}
	if ($jbconfig ['account']->get ( 'ca_needs_approved' ) == 0)
		updateUserType ( JBJOB_SEEKER_USER, $user_id );
	require_once (JPATH_COMPONENT_SITE . DS . 'models' . DS . 'japermissions.php');
	$permission_model = new JobBoardModelJAPermissions ( );
	$permission_model->initial_per ( $user->id, 'Job Seeker User' );
	require_once (JPATH_COMPONENT_SITE . DS . 'models' . DS . 'jatransactions.php');
	$transaction_model = new JobBoardModeljaTransactions ( );
	$transaction_model->store ( $user_id );

}

function exists_EmailTemplate($temp_name, $subscription_id = 0, $paymentconfig_id = 0) {
	$db = JFactory::getDBO ();
	
	$client = & JApplicationHelper::getClientInfo ( 0 );
	$params = JComponentHelper::getParams ( 'com_languages' );
	$language = $params->get ( $client->name, 'en-GB' );
	
	$query = "SELECT * FROM #__ja_email WHERE name='$temp_name' and language='$language' and  published=1";
	
	if ($paymentconfig_id)
		$query .= " and paymentconfig_id='$paymentconfig_id'";
	elseif ($subscription_id)
		$query .= " and subscription_id='$subscription_id'";
	$db->setQuery ( $query );
	$template = $db->loadObject ();
	
	if (is_null($template) && $language != 'en-GB') {
		$query = "SELECT * FROM #__ja_email WHERE name='$temp_name' and language='en-GB' and  published=1";
		if ($paymentconfig_id)
			$query .= " and paymentconfig_id='$paymentconfig_id'";
		elseif ($subscription_id)
			$query .= " and subscription_id='$subscription_id'";
		
		$db->setQuery ( $query );
		$template = $db->loadObject ();
	}
	if (is_null($template) && $paymentconfig_id && $subscription_id) {
		$query = "SELECT * FROM #__ja_email WHERE name='$temp_name' and language='$language' and  published=1";		
		$db->setQuery ( $query );
		$template = $db->loadObject ();
	}
	if (is_null($template) && $language != 'en-GB') {
		$query = "SELECT * FROM #__ja_email WHERE name='$temp_name' and language='en-GB' and  published=1";		
		$db->setQuery ( $query );
		$template = $db->loadObject ();
	}
	
	return $template;
}

/**
 * Enter description here...
 *
 * @param unknown_type $arr_link
 * @param unknown_type $temp_name
 * @param unknown_type $include_content
 * @return unknown
 */
function get_EmailTemplate($arr_link, $template, $include_content = '') {
	
	global $jbconfig, $mainframe;
	
	$db = JFactory::getDBO ();
	
	if (! is_object ( $template )) {
		$template = exists_EmailTemplate ( $template );
	}
	
	if ($template && is_object ( $template )) {
		foreach ( $arr_link as $table_name => $id ) {
			if (is_string($table_name)) {
				if ($table_name != 'friend_mail' && (count ( explode ( ',', $arr_link [$table_name] ) ) == 1)) {
					$query = 'SELECT * FROM #__' . $table_name . ' WHERE id=' . ( int ) $id;
					$db->setQuery ( $query );
					$arr_link [$table_name] = $db->loadObject ();
					if ($id != 0) {
						if (isset ( $arr_link [$table_name]->user_id )) {
							$user = JFactory::getUser ( $arr_link [$table_name]->user_id );
							$arr_link [$table_name]->user_id = $user->name;
						}
						if (isset ( $arr_link [$table_name]->user_id ))
							if ($arr_link [$table_name]->user_id == '0' || ! $arr_link [$table_name]->user_id)
								$arr_link [$table_name]->user_id = JRequest::getVar ( 'guest_name' );
					} else {
						if ($template->name == 'ApplicationMailConfirm' || $template->name == 'ApplicationMailToEmployer' || $template->name == 'mail_to_jobseeker_as_read') {
							$arr_link [$table_name]->user_id = JRequest::getVar ( 'guest_name' );
						}
					}
					if ($table_name == 'ja_jobs') {
						$query = 'SELECT count(id) AS apps FROM #__ja_applications' . ' WHERE job_id=' . ( int ) $id;
						$db->setQuery ( $query );
						$temp = $db->loadObject ();
						if (isset ( $temp ))
							$arr_link [$table_name]->apps = $temp->apps;
						else
							$arr_link [$table_name]->apps = 0;
					}
					if ($table_name == 'ja_jobalerts') {
						if ($arr_link [$table_name]->category) {
							$query = "SELECT name FROM #__ja_categories WHERE id IN (" . $arr_link [$table_name]->category . ")";
							$db->setQuery ( $query );
							$result = $db->loadResultArray ();
							if ($result)
								$arr_link [$table_name]->category = implode ( ',', $result );
						}
						if ($arr_link [$table_name]->location) {
							$query = "SELECT name FROM #__ja_location WHERE id =" . ( int ) $arr_link [$table_name]->location;
							$db->setQuery ( $query );
							$result = $db->loadResult ();
							if ($result)
								$arr_link [$table_name]->location = $result;
						}
					}
				
				} elseif ($table_name == 'ja_jobs') {
					
					if (count ( explode ( ',', $arr_link [$table_name] ) ) > 1) {
						if( substr($id, strlen($id)-2 == "," ) && strlen($id) > 2)
							$id = substr($id, 0, strlen($id)-1);
						$query = 'SELECT * FROM #__' . $table_name . ' WHERE id IN (' . $id . ')';
						$db->setQuery ( $query );
						$arr_link [$table_name] = $db->loadObjectList ();
					}
				
				}
				$emailConfig = JobBoardConstant::getEmailConfig ();
				
				if (($table_name == 'users') && ($id == 0)) {
					$arr_link [$table_name] = new stdClass ( );
					$arr_link [$table_name]->name = JText::_ ( 'Guest' );
					$arr_link [$table_name]->email = JRequest::getVar ( 'youremail' );
					$arr_link [$table_name]->username = JText::_ ( 'Guest' );
				}
				if ($table_name == 'ja_transactions') {
					if ($arr_link [$table_name]->completed == 0)
						$arr_link [$table_name]->completed = JText::_ ( 'Waitings' );
					else
						$arr_link [$table_name]->completed = JText::_ ( 'Completed' );
					$product_table_name = '';
					switch ($arr_link [$table_name]->product_type) {
						case 'P' :
							switch ($arr_link [$table_name]->value_type) {
								case 'standard' :
									$arr_link [$table_name]->product_type = JText::_ ( 'Standard posting plan' );
									break;
								case 'premium' :
									$arr_link [$table_name]->product_type = JText::_ ( 'Premium posting plan' );
									break;
								case 'resume' :
									$arr_link [$table_name]->product_type = JText::_ ( 'Search resume' );
									break;
							}
							$product_table_name = 'ja_posting_plans';
							break;
						case 'S' :
							$product_table_name = 'ja_subscriptions';
							break;
						case 'C' :
							$arr_link [$table_name]->product_type = JText::_ ( 'Credit package' );
							$product_table_name = 'ja_credits';
							break;
					}
					if (isset ( $arr_link [$table_name]->payment_method )) {
						$temp = get_payment_gateways ( $arr_link [$table_name]->payment_method );
						$temp = $temp [0];
						$arr_link [$table_name]->payment_method = $temp->alias;
					}
					if (isset ( $arr_link [$table_name]->product_id ) && $product_table_name) {
						$temp = getItemByFieldName ( $product_table_name, 'id', $arr_link [$table_name]->product_id );
						if (count ( $temp ) > 0) {
							$temp = $temp [0];
							$arr_link [$table_name]->product_id = $temp->title;
						}
					}
				
				}
		
			}
		}
		$header = exists_EmailTemplate ( 'template_header' );
		$footer = exists_EmailTemplate ( 'template_footer' );
		$template->content = $header->content . '<br />' . $template->content . '<br />' . $footer->content;
		//Update email content
		$template->content = update_email_template_field ( 'content', $template, $arr_link, $emailConfig, $include_content );
		
		//Update email subject
		$template->subject = update_email_template_field ( 'subject', $template, $arr_link, $emailConfig );
		
		//Update email from address
		$template->EmailFromAddress = update_email_template_field ( 'EmailFromAddress', $template, $arr_link, $emailConfig );
		
		//Update email from name
		$template->EmailFromName = update_email_template_field ( 'EmailFromName', $template, $arr_link, $emailConfig );
		if (! $template->EmailFromAddress)
			$template->EmailFromAddress = $emailConfig ['fromemail'];
		if (! $template->EmailFromName)
			$template->EmailFromName = $emailConfig ['fromname'];
		$template->content = JFilterInput::_decode ( $template->content );
		//		$template->content = JFilterInput::clean($template->content);
		$template->subject = JFilterInput::_decode ( $template->subject );
		$template->subject = JFilterInput::clean ( $template->subject );
		return $template;
	}
	return;
}

/**
 * Enter description here...
 *
 * @param unknown_type $field
 * @param unknown_type $email_template
 * @param unknown_type $arr_link
 * @param unknown_type $emailConfig
 * @param unknown_type $include_message
 * @return unknown
 */
function update_email_template_field($field, $email_template, $arr_link, $emailConfig, $include_message = '') {
	
	global $mainframe;
	$spec_str = getSpec_Str ( '{', '}', $email_template->{$field} );
	if (is_array ( $spec_str )) {
		foreach ( $spec_str as $spec ) {
			
			$arr_spec = explode ( '.', $spec );
			switch (strtolower ( $arr_spec [0] )) {
				case 'config' :
					$email_template->{$field} = str_replace ( '{' . $spec . '}', $emailConfig [strtolower ( $arr_spec [1] )], $email_template->{$field} );
					break;
				default :
					
					switch (strtolower ( $arr_spec [1] )) {
						case 'itemlink' :
							$root_url = str_replace("administrator/", "", JURI::base () );
							if ($arr_spec [2])
								if (strtolower ( $arr_spec [0] ) != 'ja_jobalerts')
									$email_template->{$field} = str_replace ( '{' . $spec . '}', "<a href='" . $root_url . "index.php?option=" . JBCOMNAME . "&view=" . strtolower ( 'ja' . substr ( $arr_spec [0], 3 ) ) . "&layout=jaview&from=email&cid[]=" . $arr_link [strtolower ( $arr_spec [0] )]->id . "'>" . $arr_link [strtolower ( $arr_spec [0] )]->{strtolower ( $arr_spec [2] )} . "</a>", $email_template->{$field} );
								else 
									$email_template->{$field} = str_replace ( '{' . $spec . '}', "<a href='" . $root_url . "index.php?option=" . JBCOMNAME . "&view=" . strtolower ( 'ja' . substr ( $arr_spec [0], 3 ) ) . "&layout=form&from=email&cid[]=" . $arr_link [strtolower ( $arr_spec [0] )]->id . "'>" . $arr_link [strtolower ( $arr_spec [0] )]->{strtolower ( $arr_spec [2] )} . "</a>", $email_template->{$field} );
							break;
						case 'admin_itemlink' :
							if ($arr_spec [2])
								$email_template->{$field} = str_replace ( '{' . $spec . '}', "<a href='" . JURI::base () . "administrator/index.php?option=" . JBCOMNAME . "&view=ja" . strtolower ( substr ( $arr_spec [0], 3 ) ) . "&task=edit&cid[]=" . $arr_link [strtolower ( $arr_spec [0] )]->id . "'>" . $arr_link [strtolower ( $arr_spec [0] )]->{strtolower ( $arr_spec [2] )} . "</a>", $email_template->{$field} );
							break;
						case 'include_message' :
							if (isset ( $include_message ))
								$email_template->{$field} = str_replace ( '{' . $spec . '}', $include_message, $email_template->{$field} );
							break;
						case 'friend_mail' :
							if ($include_message != '')
								$email_template->{$field} = str_replace ( '{' . $spec . '}', $arr_link ['friend_mail'], $email_template->{$field} );
							break;
						case 'joblist' :
							$temp = '<br />';
							if (! is_array ( $arr_link [strtolower ( $arr_spec [0] )] )) {
								$temp_value = $arr_link [strtolower ( $arr_spec [0] )];
								$arr_link [strtolower ( $arr_spec [0] )] = array ();
								$arr_link [strtolower ( $arr_spec [0] )] [0] = $temp_value;
							}
							
							for($i = 0; $i < count ( $arr_link [strtolower ( $arr_spec [0] )] ); $i ++)
								if (isset ( $arr_link [strtolower ( $arr_spec [0] )] [$i]->id ))
									$temp .= "<a href='" . JURI::base () . "/index.php?option=" . JBCOMNAME . "&view=" . strtolower ( 'ja' . substr ( $arr_spec [0], 3 ) ) . "&layout=jaview&cid[]=" . $arr_link [strtolower ( $arr_spec [0] )] [$i]->id . "'>" . $arr_link [strtolower ( $arr_spec [0] )] [$i]->{strtolower ( $arr_spec [2] )} . "</a> <br />";
							$email_template->{$field} = str_replace ( '{' . $spec . '}', $temp, $email_template->{$field} );
							break;
						default :
							if (isset ( $arr_link [strtolower ( $arr_spec [0] )] ))
								$email_template->{$field} = str_replace ( '{' . $spec . '}', $arr_link [strtolower ( $arr_spec [0] )]->{strtolower ( $arr_spec [1] )}, $email_template->{$field} );
							break;
					
					}
					break;
			
			}
		
		}
	}	
	return $email_template->{$field};
}

/**
 * 
 * Enter description here...
 *
 * @param unknown_type $open
 * @param unknown_type $close
 * @param unknown_type $str
 * @return unknown
 */
function getSpec_Str($open, $close, $str) {
	$arr_spec = array ();
	$count = 0;
	for($i = 0; $i <= strlen ( $str ); $i ++) {
		$temp = substr ( $str, $i, 1 );
		if (isset ( $temp ) && $temp == $open) {
			$begin = $i + 1;
		}
		if (isset ( $temp ) && $temp == $close) {
			$end = $i;
			$arr_spec [$count] = substr ( $str, $begin, $end - $begin );
			$count ++;
		}
	}
	return $arr_spec;
}

/**
 * Enter description here...
 *
 * @param unknown_type $userid
 * @return unknown
 */
function getCustomerProfile($userid) {
	$db = JFactory::getDBO ();
	$query = 'SELECT l.name,p.* FROM #__ja_profiles as p LEFT JOIN #__ja_location as l ON p.location_id=l.id WHERE user_id=' . ( int ) $userid;
	$db->setQuery ( $query );
	$customer = $db->loadObject ();
	return $customer;
}

/**
 * Enter description here...
 *
 * @param unknown_type $id
 * @return unknown
 */
function getSubLocation($id) {
	$arr_id = array ();
	$arr_id [] = $id;
	$n = count ( $arr_id );
	$db = JFactory::getDBO ();
	for($i = 0; $i < $n; $i ++) {
		$location_id = $arr_id [$i];
		$query = 'SELECT id FROM #__ja_location WHERE parent_id=' . ( int ) $location_id;
		$db->setQuery ( $query );
		$result = $db->loadObjectList ();
		if (is_array ( $result ))
			foreach ( $result as $result_id ) {
				$arr_id [] = $result_id->id;
				$n ++;
			}
	}
	$str_id = implode ( ',', $arr_id );
	return $str_id;
}

/**
 * Enter description here...
 *
 * @param unknown_type $is_hotjob
 * @param unknown_type $duration
 * @param unknown_type $user_id
 * @return unknown
 */
function checkJobsExpired($is_hotjob = 0, $duration = 0, $user_id = 0) {
	global $jbconfig;
	
	if (($duration == 0) || ($duration == null))
		return false;
	$db = JFactory::getDBO ();
	$query = 'SELECT id,user_id FROM #__ja_jobs WHERE (status="Approved") and is_hotjob=' . ( int ) $is_hotjob;
	if ($duration)
		$query .= " AND (DATEDIFF(now(), effected_date)>=$duration) AND ( expiry_date <= now() OR expiry_date is NULL ) ";
	if ($user_id)
		$query .= " AND (user_id='$user_id') ";
	$query .=" LIMIT 0,50";
	$db->setQuery ( $query );
	return $db->loadObjectList ();
}

/**
 * Enter description here...
 *
 * @param unknown_type $list_job
 * @param unknown_type $emailtemplate_name
 */
function sendMail_JobExpired($list_job, $emailtemplate_name = 'JobMailExpired') {
	$db = JFactory::getDBO ();
	
	$list_id = array ();
	if ($list_job) {
		foreach ( $list_job as $job ) {
			$user = JFactory::getUser ( $job->user_id );
			$db = JFactory::getDBO ();
			$query = "SELECT id FROM #__ja_profiles WHERE user_id=" . ( int ) $job->user_id;
			$db->setQuery ( $query );
			$profile = $db->loadObject ();
			$arr_link = array ();
			$arr_link ['ja_jobs'] = $job->id;
			$arr_link ['ja_profiles'] = $profile->id;
			$arr_link ['users'] = $user->id;
			$mail = get_EmailTemplate ( $arr_link, $emailtemplate_name );
			
			if ($mail) {
				sendMail ( $user->email, $user->name, $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName );
			}
			
			$list_id [] = $job->id;
		}
		
		$str_list_id = implode ( ',', $list_id );
		$query = "UPDATE #__ja_jobs SET status='Expired' WHERE id IN ($str_list_id)";
		$db->setQuery ( $query );
		$db->query ();
	}
}

/**
 * Enter description here...
 *
 * @param unknown_type $id
 * @return unknown
 */
function getSubCategory($id) {
	$arr_id = array ();
	$arr_id [] = $id;
	$n = count ( $arr_id );
	$db = JFactory::getDBO ();
	for($i = 0; $i < $n; $i ++) {
		$location_id = $arr_id [$i];
		$query = 'SELECT id FROM #__ja_categories WHERE parent_id=' . ( int ) $location_id;
		$db->setQuery ( $query );
		$result = $db->loadObjectList ();
		if (is_array ( $result ))
			foreach ( $result as $result_id ) {
				$arr_id [] = $result_id->id;
				$n ++;
			}
	}
	$str_id = implode ( ',', $arr_id );
	return $str_id;
}

/**
 * Enter description here...
 *
 * @param unknown_type $str_ids
 * @return unknown
 */
function getCategories($str_ids) {
	if(empty($str_ids))
		return "";
	$db = JFactory::getDBO ();
	
	$query = "SELECT name FROM #__ja_categories WHERE id in ($str_ids)";
	$db->setQuery ( $query );
	$names = $db->loadResultArray ();
	$result = '';
	if ($names)
		$result = implode ( ', ', $names );
	return $result;
}

function getLocation($str_ids) {
	if(empty($str_ids))
		return "";
	$db = JFactory::getDBO ();
	if (trim($str_ids) == "")
		return "";
	$query = "SELECT name FROM #__ja_location WHERE id in ($str_ids)";
	$db->setQuery ( $query );
	$names = $db->loadResultArray ();
	$result = '';
	if ($names)
		$result = implode ( ', ', $names );
	return $result;
}

/**
 * Enter description here...
 *
 * @return unknown
 */
function getLocations() {
	$db = & JFactory::getDBO ();
	$query = "SELECT id, name FROM #__ja_location WHERE (parent_id = 0 OR ISNULL(parent_id)) AND published = 1";
	$db->setQuery ( $query );
	$locations = $db->loadObjectList ();
	return $locations;
}

/**
 * Enter description here...
 *
 * @return unknown
 */
function getEmployerList() {
	$db = JFactory::getDBO ();
	$query = "SELECT id FROM #__users";
	$db->setQuery ( $query );
	$result = $db->loadObjectList ();
	$count = 0;
	$userObjectList = array ();
	if (is_array ( $result ))
		foreach ( $result as $user_id ) {
			$user = JFactory::getUser ( $user_id->id );
			if ($user->getParam ( 'usertype' ) == JBEMPLOYER_USER) {
				$userObjectList [$count]->id = $user->id;
				$userObjectList [$count]->name = $user->name;
				$count ++;
			}
		}
	return $userObjectList;
}

/**
 * Get type of curent user
 *
 * @return string: user's type
 */
function getCurrentUserType($user_id = 0) 

{
	if ($user_id != 0)
		$user = JFactory::getUser ( $user_id );
	else
		$user = & JFactory::getUser ();
	
	$usertype = $user->getParam ( 'usertype' );
	if ($usertype)
		return $usertype;
	else
		return 'Guest';
}

/**
 * Enter description here...
 *
 * @param unknown_type $user_id
 * @return unknown
 */
function checkSearchResumeExpired($user_id = 0) {
	global $jbconfig;
	
	if ($jbconfig ['billing']->get ( 'subscription_fee_enabled' )) {
		$format_date = $jbconfig ['general']->get ( 'format_date' );
		if ($user_id == null) {
			
			$user = JFactory::getUser ();
			$user_id = $user->id;
		}
		$db = JFactory::getDBO ();
		$query = "SELECT * FROM #__ja_employers WHERE user_id=" . ( int ) $user_id;
		$db->setQuery ( $query );
		$employer = $db->loadObject ();
		if ((($employer->begin_date_search_resume == '0000-00-00 00:00:00') && ($employer->end_date_search_resume == '0000-00-00 00:00:00')) || (($employer->begin_date_search_resume == null) && ($employer->end_date_search_resume == null)))
			return 'not';
		$timeNow = mkTimeFromDBDate ( date ( 'Y-m-d H:i:s' ) );
		$begin = mkTimeFromDBDate ( $employer->begin_date_search_resume );
		$end = mkTimeFromDBDate ( $employer->end_date_search_resume );
		if (($timeNow > $end))
			return 'expired';
		elseif ($timeNow < $begin)
			return 'future';
		else
			return 'accepted';
	} else
		return 'accepted';

}

/**
 * Enter description here...
 *
 * @param unknown_type $user_id
 * @return unknown
 */
function getAccountByUserID($user_id = 0) {
	$db = JFactory::getDBO ();
	$sql = "SELECT * FROM #__ja_employers WHERE user_id=" . ( int ) $user_id;
	$db->setQuery ( $sql );
	$acc = $db->loadObject ();
	
	return $acc;
}

/**
 * Enter description here...
 *
 * @param unknown_type $type
 * @param unknown_type $user_id
 */
function updateUserType($type, $user_id = 0) {
	if ($user_id != 0)
		$user = JFactory::getUser ( $user_id );
	else
		$user = & JFactory::getUser ();
	
	$user->setParam ( 'usertype', $type );
	$user->save ();

}

/**
 * Enter description here...
 *
 * @param unknown_type $user_id
 * @return unknown
 */
function getUserType($user_id) {
	$user = & JFactory::getUser ( $user_id );
	$usertype = $user->getParam ( 'usertype' );
	if ($usertype)
		return $usertype;
	else
		return 'Guest';
}

/**
 * Enter description here...
 *
 */
function get_sys_invoice() {
	global $sys_invoice, $jbconfig;
	$sys_invoice->username = $jbconfig ['payment']->get ( 'sys_invoice_username' );
	$sys_invoice->company = $jbconfig ['payment']->get ( 'sys_invoice_company' );
	$sys_invoice->email = $jbconfig ['payment']->get ( 'sys_invoice_email' );
	$sys_invoice->country_code = "+84";
	$sys_invoice->phone_number = $jbconfig ['payment']->get ( 'sys_invoice_phone' );
	$sys_invoice->location = $jbconfig ['payment']->get ( 'sys_invoice_location' );
}

/**
 * Enter description here...
 *
 * @param unknown_type $user_per
 * @param unknown_type $usergroup
 * @return unknown
 */
function parsePermission($user_per = 0, $usergroup = 'user') {
	global $permission, $permissionText;
	$rows = array ();
	$selected = array ();
	
	foreach ( $permission [$usergroup] as $k => $per ) {
		$std = new stdClass ( );
		
		$std->text = $permissionText [$usergroup] [$k];
		$std->value = $per;
		$std->name = $k;
		if ((intval ( $user_per ) & intval ( $std->value )) > 0)
			$selected [] = $std->value;
		else
			$selected [] = 0;
		
		$rows [] = $std;
	}
	
	return array ($rows, $selected );

}

/**
 * Enter description here...
 *
 * @param unknown_type $user_id
 * @return unknown
 */
function getPermissionByUserID($user_id = 0) {
	$db = JFactory::getDBO ();
	
	if ($user_id) {
		$query = "SELECT p.permission FROM  #__ja_permissions as p WHERE p.user_id='$user_id'";
		
		$db->setQuery ( $query );
		$result = $db->loadResult ();
		if ($result == null)
			return - 1;
		return $result;
	}
	return - 1;
}

/**
 * Enter description here...
 *
 * @param unknown_type $item
 * @param unknown_type $fieldList
 * @return unknown
 */
function parse_content_item($item, $fieldList) {
	$db = JFactory::getDBO ();
	
	foreach ( $fieldList as $field ) {
		if (in_array ( $field->field_type, array ('MSELECT', 'CHECKBOXLIST', "RADIO" ) )) {
			if (! is_array ( $item->{$field->field_name} ))
				$item->{$field->field_name} = explode ( ',', $item->{$field->field_name} );
			if (isset ( $item->{$field->field_name . '_tmp'} ))
				if (! is_array ( $item->{$field->field_name . '_tmp'} ))
					$item->{$field->field_name . '_tmp'} = explode ( ',', $item->{$field->field_name . '_tmp'} );
		
		}
	}
	
	return $item;
}

/**
 * Enter description here...
 *
 * @param unknown_type $table_name
 * @param unknown_type $where
 * @param unknown_type $published
 * @param unknown_type $inc_status
 * @return unknown
 */
function getEditFieldList($table_name, $where = '', $published = 1, $inc_status = '') {
	$db = &JFactory::getDBO ();
	$query = "SELECT f.*" . " FROM #__ja_form_fields AS f" . " WHERE  f.field_name!='' AND table_name = '$table_name' AND (f.field_state = 'chg' OR f.field_state = 'add' $inc_status)  AND f.published=" . ( int ) $published . $where . " ORDER BY f.field_ordering";
	$db->setQuery ( $query );
	//print_r($db->getQuery($query));exit;
	$fieldListEdit = $db->loadObjectList ();
	return $fieldListEdit;
}

/**
 * Enter description here...
 *
 * @param unknown_type $table_name
 * @param unknown_type $where
 * @return unknown
 */
function getFieldList($table_name, $where = '') {
	$db = &JFactory::getDBO ();
	
	$query = "SELECT fl.field_width AS column_width,fl.*, ff.*, CONCAT('a.', ff.field_name) AS sort_field_name " . " FROM #__ja_form_lists AS fl " . " LEFT JOIN #__ja_form_fields AS ff ON fl.field_id = ff.id " . " WHERE ff.field_name!='' AND ff.table_name = '$table_name' AND (ff.field_state = 'chg' OR ff.field_state = 'add') AND ff.published=1 $where" . " ORDER BY fl.ordering";
	$db->setQuery ( $query );
	
	$fieldList = $db->loadObjectList ();
	
	return $fieldList;
}

/**
 * Enter description here...
 *
 * @param unknown_type $per1
 * @param unknown_type $per2
 * @return unknown
 */
function merge2UserPermission($per1, $per2) {
	$arr_result = array ();
	$arr_result [] = $per1;
	$arr_result [] = $per2;
	$result = mergeUserPermission ( $arr_result );
	return $result;
}

/**
 * Enter description here...
 *
 * @param unknown_type $arr_per
 * @return unknown
 */
function mergeUserPermission($arr_per) {
	$result = parsePermission ( 0 );
	for($i = 0; $i < count ( $arr_per ); $i ++) {
		for($j = 0; $j < count ( $arr_per [$i] [1] ); $j ++) {
			if ($arr_per [$i] [1] [$j] > 0)
				$result [1] [$j] = $arr_per [$i] [1] [$j];
		}
	}
	return $result;
}

/**
 * Enter description here...
 *
 * @param unknown_type $user_id
 * @return unknown
 */
function getSubScriptionByUserID($user_id) {
	$db = JFactory::getDBO ();
	$query = 'SELECT s.permission FROM #__ja_subscriptions_invoice AS s WHERE s.user_id=' . ( int ) $user_id;
	$db->setQuery ( $query );
	$arr_result = $db->loadResultArray ();
	for($i = 0; $i < count ( $arr_result ); $i ++)
		$parse_script [] = parsePermission ( $arr_result [$i] );
	$result = mergeUserPermission ( $parse_script );
	return $result;
}

/**
 * Enter description here...
 *
 * @param unknown_type $permission_name
 * @return unknown
 */
function checkPermission($permission_name, $wnMessage = "Access denied. You don't have permission", $redirect = true, $raiseWarning = false) {
	global $jbconfig, $permission, $mainframe, $option;
	$tmpl = JRequest::getVar ( 'tmpl' );
	$ajax = JRequest::getVar ( 'ajax' );
	
	if ($tmpl)
		$tmpl = '&tmpl=component';
	$user = JFactory::getUser ();
	
	if (getCurrentUserType () == 'Job Seeker User')
		$item = getItemByFieldName ( 'ja_resumes', 'user_id', $user->id );
	elseif (getCurrentUserType () == 'Employer User')
		$item = getItemByFieldName ( 'ja_profiles', 'user_id', $user->id );
	
	if (isset ( $item [0] )){		
		if (! $item [0]->approved) {
			$user_permission = -1;
				JResponse::setHeader ( 'HTTP/1.0 403', true );
			if (! $ajax){
				JError::raiseWarning ( 403, JText::_ ( "Your account must be approved by Admin first to do actions" ) );
				global $mainframe;
				$mainframe->logout();
			}			
			return false;
		}
		else
			$user_permission = getPermissionByUserID ( $user->id );
	}
	else 
		$user_permission = getPermissionByUserID ( $user->id );
	
	if ($user->usertype == 'Administrator' || $user->usertype == 'Super Administrator')
		return;
	
	if (($user_permission != - 1) && ($user_permission & $permission ['user'] [$permission_name]) != $permission ['user'] [$permission_name]) {
		if ($permission_name != 'can_search_resume') {
			JResponse::setHeader ( 'HTTP/1.0 403', true );
			if( $redirect ){
				if (! $ajax)
					JError::raiseWarning ( 403, JText::_ ( $wnMessage ) );
				return $mainframe->redirect ( JRoute::_ ( "index.php?option=com_jajobboard&view=jaerrors" . $tmpl . "&Itemid=1000" ) );
			}else {
				if( $raiseWarning )
					JError::raiseWarning ( 403, JText::_ ( $wnMessage ) );
				else echo JText::_ ( $wnMessage );
				return false;
			}
		} else if (check_search_resume_package ())
			return true;
		else
			return false;
	} elseif ($user_permission==-1) {
		if( isset($jbconfig ['group_permission']) )
			$guest_permission = $jbconfig ['group_permission']->get ( 'Guest_permission', '0' );
		else $guest_permission = "";
		if (isset ( $permission ['guest'] [$permission_name] )) {
			if (($guest_permission & $permission ['guest'] [$permission_name]) != $permission ['guest'] [$permission_name]) {
				JResponse::setHeader ( 'HTTP/1.0 403', true );
				if( $redirect ){
					if (! $ajax)
						JError::raiseWarning ( 403, JText::_ ( $wnMessage ) );
					return $mainframe->redirect ( JRoute::_ ( "index.php?option=com_jajobboard&view=jaerrors" . $tmpl . "&layout=default&Itemid=1000" ) );
				}else {
					if( $raiseWarning )
						JError::raiseWarning ( 403, JText::_ ( $wnMessage ) );
					else echo JText::_ ( $wnMessage );
					return false;
				}
			}
		} else
			return false;
	}
	return true;
}

function checkPermissionAsGuest($permission_name, $wnMessage = "Access denied. You don't have permission", $redirect = true, $raiseWarning = false) {
	global $jbconfig, $permission, $mainframe, $option;
	$tmpl = JRequest::getVar ( 'tmpl' );
	$ajax = JRequest::getVar ( 'ajax' );
	
	if ($tmpl)
		$tmpl = '&tmpl=component';
	$user = JFactory::getUser ();
		
	if ($user->usertype == 'Administrator' || $user->usertype == 'Super Administrator')
		return;
	
	if( isset($jbconfig ['group_permission']) )
		$guest_permission = $jbconfig ['group_permission']->get ( 'Guest_permission', '0' );
	else $guest_permission = "";
	if (isset ( $permission ['guest'] [$permission_name] )) {
		if (($guest_permission & $permission ['guest'] [$permission_name]) != $permission ['guest'] [$permission_name]) {
			JResponse::setHeader ( 'HTTP/1.0 403', true );
			if( $redirect ){
				if (! $ajax)
					JError::raiseWarning ( 403, JText::_ ( $wnMessage ) );
				return $mainframe->redirect ( JRoute::_ ( "index.php?option=com_jajobboard&view=jaerrors" . $tmpl . "&layout=default&Itemid=1000" ) );
			}else {
				if( $raiseWarning )
					JError::raiseWarning ( 403, JText::_ ( $wnMessage ) );
				else echo JText::_ ( $wnMessage );
				return false;
			}
		}
	} else
		return false;
	
	return true;
}

/**
 * Enter description here...
 *
 * @param unknown_type $permission_name
 * @return unknown
 */
function checkPermission_Administrator($permission_name) {
	global $jbconfig, $permission, $mainframe, $option;
	$user = JFactory::getUser ();
	if ($user->usertype == 'Super Administrator' || $user->usertype == 'Manager')
		return true;
	$user_permission = getPermissionByUserID ( $user->id );
	if (($user_permission && ($user_permission & $permission ['admin'] [$permission_name]) != $permission ['admin'] [$permission_name]) || ! $user_permission) {
		JResponse::setHeader ( 'HTTP/1.0 403', true );
		JError::raiseWarning ( 403, JText::_ ( "Access denied. You don't have permission." ) );
		echo '<br /><a class="button" href="#" onclick="window.history.go(-1);">' . JText::_ ( 'Back' ) . '</a>';
		return $mainframe->redirect ( JRoute::_ ( "index.php?option=com_jajobboard" ) );
	}
	return true;

}

/**
 * Enter description here...
 *
 * @param unknown_type $i
 * @param unknown_type $condition
 * @param unknown_type $task
 * @param unknown_type $alt
 * @param unknown_type $enabled
 * @param unknown_type $limitstart
 * @return unknown
 */
function ShowUpIcon($i, $condition = true, $task = 'orderup', $alt = 'Move Up', $enabled = true, $limitstart) {
	global $mainframe;
	$alt = JText::_ ( $alt );
	
	$html = '&nbsp;';
	if (($i > 0 || ($i + $limitstart > 0)) && $condition) {
		if ($enabled) {
			$html = '<a href="#reorder" onclick="return listItemTask(\'cb' . $i . '\',\'' . $task . '\')" title="' . $alt . '">';
			$html .= '   <img src="' . $mainframe->getCfg ( 'live_site' ) . '/components/' . JBCOMNAME . '/images/uparrow.png" width="16" height="16" border="0" alt="' . $alt . '" />';
			$html .= '</a>';
		} else {
			$html = '<img src="' . $mainframe->getCfg ( 'live_site' ) . '/components/' . JBCOMNAME . '/images/uparrow0.png" width="16" height="16" border="0" alt="' . $alt . '" />';
		}
	}
	
	return $html;
}

/**
 * Enter description here...
 *
 * @param unknown_type $i
 * @param unknown_type $n
 * @param unknown_type $condition
 * @param unknown_type $task
 * @param unknown_type $alt
 * @param unknown_type $enabled
 * @param unknown_type $limitstart
 * @param unknown_type $total
 * @return unknown
 */
function ShowDownIcon($i, $n, $condition = true, $task = 'orderdown', $alt = 'Move Down', $enabled = true, $limitstart, $total) {
	global $mainframe;
	$alt = JText::_ ( $alt );
	
	$html = '&nbsp;';
	if (($i < $n - 1 || $i + $limitstart < $total - 1) && $condition) {
		if ($enabled) {
			$html = '<a href="#reorder" onclick="return listItemTask(\'cb' . $i . '\',\'' . $task . '\')" title="' . $alt . '">';
			$html .= '  <img src="' . $mainframe->getCfg ( 'live_site' ) . '/components/' . JBCOMNAME . '/images/downarrow.png" width="16" height="16" border="0" alt="' . $alt . '" />';
			$html .= '</a>';
		} else {
			$html = '<img src="' . $mainframe->getCfg ( 'live_site' ) . '/components/' . JBCOMNAME . '/images/downarrow0.png" width="16" height="16" border="0" alt="' . $alt . '" />';
		}
	}
	
	return $html;
}

/**
 * Enter description here...
 *
 * @param unknown_type $userid
 * @return unknown
 */
function getUser($userid) {
	$db = &JFactory::getDBO ();
	$query = "SELECT * FROM #__users WHERE id=" . ( int ) $userid;
	$db->setQuery ( $query );
	return $db->loadObject ();
}

/**
 * Enter description here...
 *
 * @param unknown_type $userid
 * @return unknown
 */
function getUsername($userid) {
	$db = &JFactory::getDBO ();
	$query = "SELECT username FROM #__users WHERE id=" . ( int ) $userid;
	$db->setQuery ( $query );
	return $db->loadReSult ();
}

/**
 * Enter description here...
 *
 * @param unknown_type $username
 * @return unknown
 */
function getUserId($username) {
	$db = &JFactory::getDBO ();
	$query = "SELECT id FROM #__users WHERE username='$username'";
	$db->setQuery ( $query );
	return $db->loadReSult ();
}

function getUserIds($usernames='0') {
	$db = &JFactory::getDBO ();
	$query = "SELECT distinct id FROM #__users WHERE username in ($usernames)";
	$db->setQuery ( $query );
	return $db->loadReSultArray ();
}

/**
 * Enter description here...
 *
 * @param unknown_type $userid
 * @return unknown
 */
function getUserinfo($userid) {
	$db = JFactory::getDBO ();
	$query = "SELECT u.username,u.email,p.company,l.name as location,p.email,p.tel " . "\n FROM #__ja_profiles p " . "\n INNER JOIN #__users u ON u.id=p.user_id AND p.user_id = '$userid' " . "\n LEFT JOIN #__ja_location l ON u.id=p.location_id";
	
	$db->setQuery ( $query ); //print_r($db->getQuery($query));echo '<br>';
	$row = $db->loadObject ();
	return $row;
}

/**
 * Enter description here...
 *
 * @param unknown_type $date
 * @return unknown
 */
function generateDate($date = null) {
	global $jbconfig;
	
	//$user = JFactory::getUser();
	//if ($user->id)
		//$localDate = " (".JText::_("Local time").": ".date ( str_replace ( '%', '', isset ( $jbconfig ['general'] ) ? $jbconfig ['general']->get ( 'format_date' ) : '%Y-%m-%d' ), strtotime($date) + date('Z') - $user->getParam('timezone', $config->offset)*60*60).")";
	
	if ($date)
	if ($time = strtotime ( $date )) {
		return date ( str_replace ( '%', '', isset ( $jbconfig ['general'] ) ? $jbconfig ['general']->get ( 'format_date' ) : '%Y-%m-%d' ), $time );
	} else
		return;
}

/**
 * Enter description here...
 *
 * @param unknown_type $date
 * @return unknown
 */
function mkTimeFromDBDate($date = null) {
	return strtotime ( $date );
}

/**
 * Enter description here...
 *
 * @param unknown_type $format
 * @param unknown_type $date
 * @return unknown
 */
function mkTimeFromFormat($format = 'Y-m-d H:i:s', $date) {
	return $time = getdate ( strtotime ( $date ) );
}

/**
 * Enter description here...
 *
 * @param unknown_type $controller
 * @param unknown_type $row
 * @return unknown
 */
function assign_spec_field($controller, & $row) {
	$controller = substr ( $controller, 2 );
	for($i = 0; $i < count ( $row->spec_field ); $i ++) {
		$field_name = $row->spec_field [$i] ['name'];
		$field_type = $row->spec_field [$i] ['type'];
		$userfile = JRequest::getVar ( $field_name, null, 'files', 'array' );
		if ($userfile ["name"] && $userfile ["name"] != '') {
			
			if (($field_type == 'IMAGE') || ($field_type == 'FILE')) {
				$ext_type = ($field_type == 'IMAGE') ? 'allowed_img' : 'allowed_ext';
				$file = fileUpload ( $field_name, $controller, $ext_type );
				if ($file!=JText::_( 'This file extension is not allowed to upload' )&&$file!=JText::_ ( 'Size of uploaded file is too large' )) {
					if ($row->$field_name) {
						$file_path = str_replace ( '/', '\\', JPATH_SITE . DS . $row->$field_name );
						if (! file_exists ( $file_path ))
							$file_path = str_replace ( '\\', '/', JPATH_SITE . DS . $row->$field_name );
						if (file_exists ( $file_path ))
							@JFile::delete ( $file_path );
					}
					if ($field_type == 'IMAGE') {
						$max_width = $row->spec_field [$i] ['field_width'];
						$max_height = $row->spec_field [$i] ['field_height'];
						$file = jaJBResize ( $file, $max_width, $max_height );
					}
					$row->$field_name = $file;
										
					JRequest::setVar ( $field_name, $file );
				} else {
					return false;
				}
			}
		
		} else if (($field_type == 'IMAGE') || ($field_type == 'FILE'))
			$row->$field_name = JRequest::getVar ( 'text_' . $field_name );
	
	}
	
	return true;
}

/**
 * Enter description here...
 *
 * @param unknown_type $field_name
 * @param unknown_type $controller
 * @param unknown_type $ext_type
 * @return unknown
 */
function fileUpload($field_name, $controller, $ext_type) {
	
	component_configs ();
	global $jbconfig;
	global $option;
	jimport ( 'joomla.filesystem.file' );
	// Get the uploaded file information
	$userfile = JRequest::getVar ( $field_name, null, 'files', 'array' );
	
	$arr_filename = explode ( '.', $userfile ['name'] );
	$ext = strtolower ( $arr_filename [count ( $arr_filename ) - 1] );
	$arr_ext = explode ( ',', str_replace ( ' ', '', strtolower ( $jbconfig ['general']->get ( $ext_type ) ) ) );
	
	// Make sure that file uploads are enabled in php
	if (! ( bool ) ini_get ( 'file_uploads' )) {
		JError::raiseWarning ( 'SOME_ERROR_CODE', JText::_ ( 'WARNINSTALLFILE' ) );
		return "";
	}
	
	// If there is no uploaded file, we have a problem...
	if (! is_array ( $userfile )) {
		JError::raiseWarning ( 'SOME_ERROR_CODE', JText::_ ( 'No file selected' ) );
		return "";
	}
	
	// Check if there was a problem uploading the file.
	if ($userfile ['error'] || $userfile ['size'] < 1) {
		JError::raiseWarning ( 'SOME_ERROR_CODE', JText::_ ( 'No file selected' ) );
		return "";
	}
	if ($userfile ['size'] > ( int ) $jbconfig ['general']->get ( 'max_upload_bytes' ) * 1024 * 1024) {
		JError::raiseWarning ( 'SOME_ERROR_CODE', JText::_ ( 'Size of uploaded file is too large' ) );
		setcookie ( 'upload_error_msg', JText::_ ( 'Size of uploaded file is too large' ), time () + 60 * 60 );
		return JText::_ ( 'Size of uploaded file is too large' );
	}
	
	if (! in_array ( $ext, $arr_ext )) {
		JError::raiseWarning ( 'SOME_ERROR_CODE', JText::_ ( 'This file extension is not allowed to upload' ) );
		setcookie ( 'upload_error_msg', JText::_ ( 'This file extension is not allowed to upload' ), time () + 60 * 60 );
		return JText::_ ( 'This file extension is not allowed to upload' );
	}
	
	// Build the appropriate paths

	// $tmp_dest   	= $jbconfig->getValue('config.tmp_path').DS.$userfile['name'];
	$filename 		= JFilterOutput::stringURLSafe ( JFile::stripExt ( $userfile ['name'] ) ) . '.' . JFile::getExt ( $userfile ['name'] );
	$filename		= trim($filename);
	if( $filename = "." ){		
		$filename = $userfile['name'];
	}
			
	$filename 		= date ( 'Ymdhms' ) . $filename;
	$tmp_dest 		= JPATH_SITE . DS . 'images' . DS . 'stories' . DS . "jbuploads" . DS . $controller . DS . $filename;
	$tmp_src 		= $userfile ['tmp_name'];
	
	if ( file_exists($tmp_src) )
		$uploaded = JFile::upload( $tmp_src, $tmp_dest );
		
	return 'images/stories/jbuploads/' . $controller . '/' . $filename;

}

/**
 * Enter description here...
 *
 * @param unknown_type $id
 * @param unknown_type $name
 * @return unknown
 */
function get_payment_gateways($id = 0, $name = '') {
	
	$db = JFactory::getDBO ();
	$sql = "select * from #__ja_paymentconfig where published=1";
	if (( int ) $id) {
		$sql .= " and id='$id'";
	}
	if ($name != '') {
		$sql .= " and name='$name'";
	}
	$db->setQuery ( $sql );
	$list = $db->loadObjectList ();
	$paysys = array ();
	if( is_array($list) )
		foreach ( $list as $k => $row ) {
			$vars = new stdClass ( );
			$params = new JParameter ( $row->datas );
			$vars = $params->_registry ['_default'] ['data'];
			$vars->name = $row->name;
			$vars->alias = $row->alias;
			$vars->id = $row->id;
			$vars->custom_payment_pending_mail = $row->custom_payment_pending_mail;
			$vars->custom_payment_completed_mail = $row->custom_payment_completed_mail;
			$paysys [] = $vars;
		}
	
	return $paysys;
}

/**
 * Enter description here...
 *
 * @param unknown_type $url
 * @param unknown_type $vars
 */
function encode_and_redirect($url, $vars) {
	$vars1 = array ();
	foreach ( $vars as $k => $v ) {
		$vars1 [] = urlencode ( $k ) . '=' . urlencode ( $v );
		$va [] = $k . '=' . $v;
	}
	$x = join ( '&', $vars1 );
	$y = join ( '&', $va );
	?>
<script type="text/javascript">
    	location.href = '<?php
	echo "$url?$x";
	?>';
    </script>
<?php

}

/**
 * Enter description here...
 *
 * @param unknown_type $length
 * @return unknown
 */
function get_rand($length) {
	$all_g = "ABCDEFGHIJKLMNOPQRSTWXZ";
	$pass = "";
	srand ( ( double ) microtime () * 1000000 );
	for($i = 0; $i < $length; $i ++) {
		srand ( ( double ) microtime () * 1000000 );
		$pass .= $all_g [rand ( 0, strlen ( $all_g ) - 1 )];
	}
	return $pass;
}

/**
 * Enter description here...
 *
 * @param unknown_type $user_id
 * @param unknown_type $result
 * @param unknown_type $completed
 * @param unknown_type $product_type
 * @param unknown_type $detail
 * @return unknown
 */
function make_transaction($user_id, $result = array(), $completed = 0, $product_type = '', $detail = '') {
	$db = JFactory::getDBO ();
	$row = new stdClass ( );
	
	$row->user_id = $user_id;
	$row->pay_method = $result->payment_method;
	$row->amount = $result->amount;
	$row->completed = $completed;
	$row->ip = $_SERVER ['REMOTE_ADDR'];
	$row->invoice_id = $result->invoice_id;
	$row->date = date ( "Y-m-d H:i:s" );
	$row->currency = $result->currency_code;
	$row->txn_id = $result->txn_id;
	$row->product_type = $product_type;
	$row->detail = $detail;
	$row->datas = $result->datas;
	
	$params = new JParameter ( $result->datas );
	foreach ( $result->datas as $k => $value ) {
		$params->set ( $k, $value );
	}
	$row->datas = $params->toString ();
	
	if ($db->insertObject ( "#__ja_transactions", $row )) {
		return true;
	} else {
		echo false;
	}
}

/**
 * Enter description here...
 *
 * @param unknown_type $vars
 * @return unknown
 */
function update_account_for_employer($vars) {
	$db = JFactory::getDBO ();
	return $db->updateObject ( "#__ja_employers", $vars, 'user_id' );
}

/**
 * Enter description here...
 *
 * @param unknown_type $template
 * @return unknown
 */
function getEmailTemplate($template) {
	$db = JFactory::getDBO ();
	$query = "SELECT 	*
			FROM #__ja_email
			WHERE	name='$template' and published=1";
	$db->setQuery ( $query );
	return $db->loadObject ();
}

/**
 * Enter description here...
 *
 * @param unknown_type $to
 * @param unknown_type $nameto
 * @param unknown_type $subject
 * @param unknown_type $content
 * @param unknown_type $filters
 * @param unknown_type $from
 * @param unknown_type $fromname
 * @param unknown_type $attachment
 * @param unknown_type $header
 * @return unknown
 */
function sendmail($to, $nameto, $subject, $content, $filters = "", $from = '', $fromname = '', $attachment = null, $header = true) {
	
	global $jbconfig, $mainframe;
	if ($header) {
		$header = getEmailTemplate ( "mailheader" );
		$footer = getEmailTemplate ( "mailfooter" );
		if ($header)
			$content = $header->content . "\n" . $content . "\n\n";
		if ($footer) {
			$content .= $footer->content;
		}
	}
	
	$filters ["[SITE_NAME]"] = $jbconfig ['emails']->get ( 'sitename' );
	$filters ["[SITE_URL]"] = $mainframe->getCfg ( 'live_site' );
	
	if (is_array ( $filters )) {
		foreach ( $filters as $key => $value ) {
			$subject = str_replace ( $key, $value, $subject );
			$content = str_replace ( $key, $value, $content );
		}
	}
	
	$content = stripslashes ( $content );
	$subject = stripslashes ( $subject );
	
	if (! $from)
		$from = $jbconfig ['emails']->get ( 'fromemail' );
	if (! $fromname)
		$fromname = $jbconfig ['emails']->get ( 'fromname' );
	$sendmail = 2;
	
	if ($sendmail == 1) {
		//echo mail		
		echo JText::_("Sender :") . $fromname . ' (' . $from . ")" . "<br/>";
		echo JText::_("Send to : ") . $nameto . ' (' . $to . ")" . "<br/>";
		echo JText::_("Subject:") . $subject . JText::_("<br />Content:") . str_replace ( "\n", "<br/>", $content ) . "<br />-----------------------------<br />";
		return true;
		
	} elseif ($sendmail == 2) {
		$mode = (int)$jbconfig ['emails']->get ( 'sendmode', 1 );
		$cc = null;
		if($jbconfig ['emails']->get ( 'ccemail' ))	$cc = explode ( ',', $jbconfig ['emails']->get ( 'ccemail' ) );
		if (!$mode){
				$content = strip_tags($content,'<br/><br /><p></p>');		
		}
		$content = str_replace ( "\n", "<br/>", $content );
		//send email
		
		return JUtility::sendMail($from, $fromname, $to, $subject, $content, 1, $cc, null, $attachment) ;
	}
	
}

/**
 * Enter description here...
 *
 * @param unknown_type $userid
 * @return unknown
 */
function getEmailFromUsr($userid) {
	$db = JFactory::getDBO ();
	$query = "SELECT email FROM 	#__users WHERE	id='$userid'";
	$db->setQuery ( $query );
	return $db->loadResult ();
}

/**
 * Enter description here...
 *
 * @param unknown_type $field_name
 * @return unknown
 */
function get_codes_of_field($field_name, $oder="") {
	$db = JFactory::getDBO ();
	$query = "SELECT * FROM #__ja_codes WHERE field_id='$field_name' ".$oder;
	$db->setQuery ( $query );
	return $db->loadObjectList ();
}

/**
 * Enter description here...
 *
 * @param unknown_type $table_name
 * @param unknown_type $field_name
 * @param unknown_type $value
 * @return unknown
 */
function getItemByFieldName($table_name, $field_name, $value) {
	$db = JFactory::getDBO ();
	if(empty($value)) $value = 0;
	if ($field_name != '')
		$where = " WHERE $field_name=$value";
	else
		$where = '';
	$query = "SELECT * FROM #__$table_name $where";
	$db->setQuery ( $query );
	$result = $db->loadObjectList ();
	return $result;
}

/**
 * Enter description here...
 *
 * @param unknown_type $user_id
 * @return unknown
 */
function getProfileFromUserId($user_id) {
	$db = JFactory::getDBO ();
	$query = "SELECT * FROM #__ja_profiles WHERE user_id=" . ( int ) $user_id;
	$db->setQuery ( $query );
	return $db->loadObject ();
}

/**
 * Enter description here...
 *
 * @param unknown_type $user_id
 * @return unknown
 */
function getResumeFromUserId($user_id) {
	$db = JFactory::getDBO ();
	$query = "SELECT * FROM #__ja_resumes WHERE user_id=" . ( int ) $user_id;
	$db->setQuery ( $query );
	return $db->loadObject ();
}

/**
 * Enter description here...
 *
 * @param unknown_type $item
 * @return unknown
 */
function temp_export($item) {
	$content = '## ************** ' . JText::_ ( 'Begin email template' ) . ': ' . $item ['name'] . ' ****************##' . "\r\n\r\n";
	$content .= '[Email_Template name="' . $item ['name'] . '"';
	
	if ($item ['subscription_id'])
		$content .= ' subscription_id=' . ( int ) $item ['subscription_id'];
	if ($item ['paymentconfig_id'])
		$content .= ' paymentconfig_id=' . ( int ) $item ['paymentconfig_id'];
	
	$content .= ' published="' . $item ['published'] . '" system="' . ( int ) $item ['system'] . '" group="' . ( int ) $item ['group'] . '" language="' . $item ['language'] . '"]' . "\r\n";
	
	$content .= '[title]' . "\r\n";
	$content .= $item ['title'] . "\r\n";
	
	$content .= '[subject]' . "\r\n";
	$content .= $item ['subject'] . "\r\n";
	
	$content .= '[content]' . "\r\n";
	$content .= $item ['content'] . "\r\n";
	
	$content .= '[EmailFromName]' . "\r\n";
	$content .= $item ['EmailFromName'] . "\r\n";
	
	$content .= '[EmailFromAddress]' . "\r\n";
	$content .= $item ['EmailFromAddress'] . "\r\n";
	$content .= '[/Email_Template]' . "\r\n\r\n";
	$content .= '## ************** ' . JText::_ ( 'End email template' ) . ': ' . $item ['name'] . ' ****************##' . "\r\n\r\n\r\n\r\n\r\n\r\n";
	
	return $content;
}

/**
 * Enter description here...
 *
 */
function auto_check_jobs_expire() {
	global $jbconfig;
	$db = JFactory::getDBO ();
	$userdetail = JRequest::getVar ( 'userdetail' );
	$now = time();
	$duration_standard_post = $jbconfig ['posts']->get ( 'posts_display_days', 30 );
	$duration_check = ( int ) $jbconfig ['posts']->get ( 'check_expired_jobs_duration', 10 ) * 60 * 60;
	$checked = true;
	$checked1 = false;
	/* Check standard jobs*/
	$lastest_check = strtotime ( isset ( $jbconfig ['others'] ) ? $jbconfig ['others']->get ( 'check_job_expired_date', 10 ) : 10 );
	if (($now - $lastest_check) >= ($duration_check)) {
		$result = checkJobsExpired ( 0, $duration_standard_post );
		if ($result) {
			sendMail_JobExpired ( $result );
		}
		if (count($result)>0)
			$checked = false;
		$checked1 = true;
	}
	
	/* Check premium jobs*/
	$duration_premium_post = $jbconfig ['posts']->get ( 'posts_show_days_elapsed', 30 );
	if (($now - $lastest_check) >= ($duration_check)) {
		
		$result = checkJobsExpired ( 1, $duration_premium_post );
		if ($result) {
			
			sendMail_JobExpired ( $result );
		}
		if (count($result)>0)
			$checked = false;
		$checked1 = true;
	}
		
	if ($checked && $checked1) {
		$data = isset ( $jbconfig ['others'] ) ? $jbconfig ['others']->toString () : '';
		$data = substr($data,0,strpos($data,'check_job_expired_date')-1);
		$query = "UPDATE #__ja_config SET data='" . $data . " \ncheck_job_expired_date=" . date ( 'Y-m-d H:i:s' ) . " \nsendmail_expiredjob_completed=done"."' WHERE tab='others'";
		$db->setQuery ( $query );
		$db->query ();
	}
	elseif ($checked1) 	
	{
		$data = isset ( $jbconfig ['others'] ) ? $jbconfig ['others']->toString () : '';
		$query = "UPDATE #__ja_config SET data='" . $data . " \nsendmail_expiredjob_completed=progress"."' WHERE tab='others'";
		$db->setQuery ( $query );
		$db->query ();
	}
	
	//Job Alert - Begin - 
	

	if (isset ( $jbconfig ['jobalert_log'] )) {
		if ($jbconfig ['jobalert_log']->get ( 'lastest_sendmail' )){
			$lastest_sendmail = strtotime ( $jbconfig ['jobalert_log']->get ( 'lastest_sendmail' ) );
			if( $lastest_sendmail > time() )
				$lastest_sendmail = time();
		}else
			$lastest_sendmail = time() - 86400;
					
		if ( ( time() - $lastest_sendmail) >= 86400 ) {
			$is_completed = $jbconfig ['jobalert_log']->get ( 'is_completed', 'new' );
			
			auto_send_mail_to_jobseeker_about_job ( $is_completed );
		}
	} else {
		$query = "INSERT INTO #_ja_config VALUES (null,'',jobalert_log)";
		$db->setQuery ( $query );
		$db->query ();
	}
	//Job Alert - End - 
	

	if (($now - $lastest_check) >= ($duration_check)) {
		checkHiring ();
	}

}

/**
 * Enter description here...
 *
 */
function checkHiring() {
	global $jbconfig;
	$db = JFactory::getDBO ();
	$query = "SELECT user_id FROM #__ja_employers";
	$db->setQuery ( $query );
	$obj_employers = $db->loadObjectList ();
	require_once (JPATH_COMPONENT . DS . "models" . DS . "jajobs.php");
	$job_model = new JobBoardModelJAJobs ( );
	
	$arr_user_id = array ();
	
	for($i = 0; $i < count ( $obj_employers ); $i ++) {
		$where_more = ' and a.status=\'Approved\' ';
		$where_more .= ' AND ( a.expiry_date >= now() OR a.expiry_date is NULL ) and(a.effected_date<=now()) and ( (DATE_ADD(a.effected_date, INTERVAL ' . ( int ) $jbconfig ['posts']->get ( 'posts_display_days', 30 ) . ' DAY) >= now()  AND a.is_hotjob=0) or (DATE_ADD(a.effected_date, INTERVAL ' . ( int ) $jbconfig ['posts']->get ( 'posts_show_days_elapsed', 30 ) . ' DAY) >= now()  AND a.is_hotjob=1) )';
		$where_more .= ' and a.user_id=' . $obj_employers [$i]->user_id;
		$items = $job_model->getItems ( $where_more, 0, 200 );
		$query = "SELECT a.id FROM #__ja_jobs AS a WHERE 1=1 ";
		$query .= $where_more;
		$db->setQuery ( $query );
		$items = $db->loadObjectList ();
		if (count ( $items ) == 0)
			$arr_user_id [] = $obj_employers [$i]->user_id;
	}
	$str_user_id = implode ( ',', $arr_user_id );
	
	updateEmployer_Hiring ( $str_user_id );
}

/**
 * Enter description here...
 *
 * @param unknown_type $str_user_id
 */
function updateEmployer_Hiring($str_user_id) {
	$db = JFactory::getDBO ();
	$query = "UPDATE #__ja_employers SET hiring=0 WHERE user_id IN ($str_user_id)";
	$db->setQuery ( $query );
	$db->query ();
}

/**
 * Enter description here...
 *
 * @param unknown_type $timeStamp
 * @param unknown_type $mid
 * @return unknown
 */
function generatTimeStamp($timeStamp, $mid = 0) {
	$ago = 0;
	if ($mid == 0) {
		$cal = (time () - $timeStamp);
	} else {
		$cal = ($timeStamp - time ());
		if ($cal < 0) {
			$cal = 0 - $cal;
			$ago = 1;
		}
	}
	$d = floor ( $cal / 24 / 60 / 60 );
	$h = floor ( ($cal / 60 / 60 - $d * 24) );
	$m = floor ( ($cal / 60 - $d * 24 * 60 - $h * 60) );
	
	if ($mid == 0) {
		if ($d == 0) {
			$str = "<span class=\"class_today\">" . JText::_ ( 'Today' ) . "</span>";
		} elseif ($d == 1) {
			$str = "<span class=\"class_yesterday\">" . JText::_ ( 'Yesterday' ) . "</span>";
		} elseif ($d == 2) {
			$str = "<span class=\"class_2dayago\">2 " . JText::_ ( 'days ago' ) . "</span>";
		} else {
			//$str = generatDate($timeStamp,1);
			$str = "<span class=\"time_show\">" . $d . " ". JText::_ ( 'days ago' ) . ".</span>";
		}
		return $str;
	} else {
		if ($d == 0) {
			$str = "<span class=\"class_today\">" . JText::_ ( 'Today' ) . "</span>";
		} else {
			if ($ago == 1) {
				if ($d == 1) {
					$str = "<span class=\"class_yesterday\">" . JText::_ ( 'Yesterday' ) . "</span>";
				
				} else {
					//$str = generatDate($timeStamp,1);
					$str = "<span class=\"time_show\">" . $d . " ". JText::_ ( 'days ago' ) . ".</span>";
				}
			} else {
				if ($d == 1) {
					$str = "<span class=\"class_tomorrow\">" . JText::_ ( 'Tomorrow' ) . "</span>";
				} else {
					//$str = generatDate($timeStamp,1);
					$str = "<span class=\"time_show\">" . $d . " ". JText::_ ( 'days' ) . "</span>";
				}
			}
		}
		return $str;
	}
}

/**
 * Enter description here...
 *
 */
function show_powered_by() {
	global $jbconfig;
	//if(!$jbconfig['general']->get('is_turn_off_copyright', 0) && (!isset($jbconfig['license']) || $jbconfig['license']->get('type')!= md5 ( 'professional' ))){
	if( ! $jbconfig['general']->get('is_turn_off_copyright', 0) ){
		
	}	
}

function get_license_type() {
	global $jbconfig;
	
	if ($jbconfig ['license']->get ( 'type' ) == md5 ( 'professional' )) {
		return 'Professional';
	} elseif ($jbconfig ['license']->get ( 'type' ) == md5 ( 'standard' )) {
		return 'Standard';
	} else
		return $jbconfig ['license']->get ( 'type' );
}

/**
 * Enter description here...
 *
 * @param unknown_type $URL
 * @param unknown_type $req
 * @return unknown
 */
function curl_getdata($URL, $req) {
	$proxy = JRequest::getVar('enable_proxy', 0);
	if($proxy){
		$proxy_address 	= JRequest::getVar('proxy_address', '');
		$proxy_port 	= JRequest::getVar('proxy_port', '');
		$proxystr 		= "$proxy_address:$proxy_port";
		$proxy_user 	= JRequest::getVar('proxy_user', '');
		$proxy_pass 	= JRequest::getVar('proxy_pass', '');
		$proxyUserPass 	= "$proxy_user:$proxy_pass";
		$proxyType 		= JRequest::getVar('proxy_type', 'CURLPROXY_HTTP');		
	}
	
	$ch = curl_init ();
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
	curl_setopt ( $ch, CURLOPT_URL, $URL );
	curl_setopt ( $ch, CURLOPT_TIMEOUT, 10 );
	if( $req != "" )
	   curl_setopt ( $ch, CURLOPT_POST, true );
	else 
	   curl_setopt ( $ch, CURLOPT_POST, false );
	if( $req != "" )
	   curl_setopt ( $ch, CURLOPT_POSTFIELDS, $req );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
	
	if($proxy){
		curl_setopt($ch, CURLOPT_PROXY, $proxystr);
		curl_setopt($ch, CURLOPT_PROXYTYPE, $proxyType);
		curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyUserPass);
	}
	
	$result = curl_exec ( $ch );
	curl_close ( $ch );	
	return $result;
}

/**
 * Enter description here...
 *
 * @param unknown_type $host
 * @param unknown_type $path
 * @param unknown_type $req
 * @return unknown
 */
function socket_getdata($host, $path, $req) {
	$header = "POST $path HTTP/1.0\r\n";
	$header .= "Host: " . $host . "\r\n";
	$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
	$header .= "User-Agent:      Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0\r\n";
	$header .= "Content-Length: " . strlen ( $req ) . "\r\n\r\n";
	$header .= $req;
	set_time_limit(500);
	$fp = @fsockopen ( $host, 80, $errno, $errstr, 500 );
	if (! $fp)
		return;
	@fwrite ( $fp, $header );
	$data = '';
	$i = 0;
	do {
		$header .= @fread ( $fp, 1 );
	} while ( ! preg_match ( '/\\r\\n\\r\\n$/', $header ) );
	
	while ( ! @feof ( $fp ) ) {
		$data .= @fgets ( $fp, 128 );
	}
	fclose ( $fp );
	return $data;
}

/**
 * Enter description here...
 *
 * @return unknown
 */
function getRealIpAddr() {
	if (! empty ( $_SERVER ['HTTP_CLIENT_IP'] )) //check ip from share internet
{
		$ip = $_SERVER ['HTTP_CLIENT_IP'];
	} elseif (! empty ( $_SERVER ['HTTP_X_FORWARDED_FOR'] )) //to check ip is pass from proxy
{
		$ip = $_SERVER ['HTTP_X_FORWARDED_FOR'];
	} else {
		$ip = $_SERVER ['REMOTE_ADDR'];
	}
	return $ip;
}




function check_in_shortlist($user_id, $item_id, $listtype) {
	$db = JFactory::getDBO ();
	$query = "SELECT * FROM #__ja_shortlist WHERE user_id=" . ( int ) $user_id . " AND item_id=$item_id AND listtype='$listtype'";
	$db->setQuery ( $query );
	if (count ( $db->loadObjectList () ) >= 1)
		return true;
	return false;
}

function rend_language() {
	jimport ( 'joomla.filesystem.file' );
	$filename = 'language/vi-VN/vi-VN.com_jajobboard.ini';
	$content = JFile::read ( $filename );
	$param = new JParameter ( $content );
	
	$param_ = new JParameter ( '' );
	foreach ( $param->_registry ['_default'] ['data'] as $k => $row ) {
		$param_->set ( $k, strtolower ( $k ) );
	}
	
	$content = $param_->toString ();
	JFile::write ( 'en-GB.com_jajobboard.ini', $content );
	echo 'Thanh cong';
}

function populateDB($sqlfile, &$db, &$error) {
	$change_md_sqls = splitSql ( $sqlfile );
	foreach ( $change_md_sqls as $query ) {
		$query = trim ( $query );
		if ($query != '') {
			$db->setQuery ( $query );
			if (! $db->query ()) {
				$error [] = " Not run " . $query;
			}
		}
	}
	return $error;
}

function splitSql($sqlfile) {
	$sql = file_get_contents ( $sqlfile );
	$sql = trim ( $sql );
	$sql = preg_replace ( "/\n\#[^\n]*/", '', "\n" . $sql );
	$buffer = array ();
	$ret = array ();
	$in_string = false;
	
	for($i = 0; $i < strlen ( $sql ) - 1; $i ++) {
		if ($sql [$i] == ";" && ! $in_string) {
			$ret [] = substr ( $sql, 0, $i );
			$sql = substr ( $sql, $i + 1 );
			$i = 0;
		}
		
		if ($in_string && ($sql [$i] == $in_string) && $buffer [1] != "\\") {
			$in_string = false;
		} elseif (! $in_string && ($sql [$i] == '"' || $sql [$i] == "'") && (! isset ( $buffer [0] ) || $buffer [0] != "\\")) {
			$in_string = $sql [$i];
		}
		if (isset ( $buffer [1] )) {
			$buffer [0] = $buffer [1];
		}
		$buffer [1] = $sql [$i];
	}
	
	if (! empty ( $sql )) {
		$ret [] = $sql;
	}
	return ($ret);
}

function Install_Db() {
	//if(isset($_SESSION[md5('installed_db_jbconfig')])) return ;
	//$_SESSION[md5('installed_db_jbconfig')] = true;
	$path = JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_jajobboard' . DS . 'installer' . DS . 'sql' . DS;

	global $JBVERSION;
	// $version_list = array ('1.0.1', '1.2.0', '1.2.1', '1.2.2', '1.2.3', '1.2.4', '1.2.5', '1.3.0', '1.3.1', '1.3.2', '1.3.3', '1.4.0','1.4.1', '1.4.2', '1.4.3', '1.4.6', '1.4.7' );
	// Get version list from install folder.
	$version_list = array();
	jimport('joomla.filesystem.folder');
	$files = JFolder::files($path);
	if($files){
	   foreach ($files as $f){
			$info = pathinfo($f);
			if( strpos($info['filename'], "upgrade_v") !== false && $f != "upgrade_v1.2.sql" ){
				$version = str_replace("upgrade_v", "", $info['filename']);
				$version_list[] = $version;
			}
	   }
	}
	
	$db = JFactory::getDBO ();
	
	$q = "SELECT data FROM #__ja_config where tab='others'";
	$db->setQuery ( $q );
	$data = $db->loadResult ();
	$param = new JParameter ( $data );
	
	$var = 'installed_db_config_1_0'; //.str_replace('.', '_', $JBVERSION);
	if ($param->get ( $var, 0 ) == 0) {
		$path = JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_jajobboard' . DS . 'installer' . DS . 'sql' . DS . 'install.configData.sql';
		$error = null;
		if (file_exists ( $path )) {
			populateDB ( $path, $db, $error );
			if ($error) {
				$error = implode ( "<br/>", $error );
				return JError::raiseError ( 1, $error );
			} else {
				$param->set ( $var, 1 );
				$data = $param->toString ();
				$sql = "Update #__ja_config Set data='$data' Where tab='others'";
				$db->setQuery ( $sql );
				$db->query ();
			}
		} else {
			JError::raiseWarning ( 1, JText::_ ( 'Sql file not found. Installation process default data failed.' ) . '<br /><br />' );
		}
	}
	
	if (count ( $version_list ) > 0) {
		$err_msg = '';
		for($i = 0; $i < count ( $version_list ); $i ++) {
			$error = null;
			$filename = 'upgrade_v' . $version_list [$i];
			$var = 'upgrade_' . str_replace ( '.', '_', $version_list [$i] );
			if ($param->get ( $var, 0 ))
				continue;
						
			// 1.2.4
			if(checkField_inserted('ja_jobs', 'effected_date') && $version_list [$i]=='1.2.4'){
				$param->set ( $var, 1 );
				$data = $param->toString ();
				
				$sql = "Update #__ja_config Set data='$data' Where tab='others'";
				$db->setQuery ( $sql );
				$db->query ();
				continue;
			}
			
			// 1.2.5
			if(checkField_inserted('ja_email', 'update_date') && $version_list [$i]=='1.2.5'){
				$param->set ( $var, 1 );
				$data = $param->toString ();
				
				$sql = "Update #__ja_config Set data='$data' Where tab='others'";
				$db->setQuery ( $sql );
				$db->query ();
				continue;
			}
			
			// 1.3.0
			if(checkField_inserted('ja_xml_feeds', 'SchemaID') && $version_list [$i]=='1.3.0'){
				$param->set ( $var, 1 );
				$data = $param->toString ();
				
				$sql = "Update #__ja_config Set data='$data' Where tab='others'";
				$db->setQuery ( $sql );
				$db->query ();
				continue;
			}
			
			// 1.3.1
			if(checkField_inserted('ja_xml_feeds', 'SchemaID') && $version_list [$i]=='1.3.1'){
				$param->set ( $var, 1 );
				$data = $param->toString ();
				
				$sql = "Update #__ja_config Set data='$data' Where tab='others'";
				$db->setQuery ( $sql );
				$db->query ();
				continue;
			}
			
			// 1.3.3
			if(checkField_inserted('ja_jobalerts', 'job_distance') && $version_list [$i]=='1.3.3'){
				$param->set ( $var, 1 );
				$data = $param->toString ();
				
				$sql = "Update #__ja_config Set data='$data' Where tab='others'";
				$db->setQuery ( $sql );
				$db->query ();
				continue;
			}
			
			// 1.4.0
			if(checkField_inserted('ja_feeds', 'filter_zipcode') && $version_list [$i]=='1.4.0'){
				$param->set ( $var, 1 );
				$data = $param->toString ();
				
				$sql = "Update #__ja_config Set data='$data' Where tab='others'";
				$db->setQuery ( $sql );
				$db->query ();
				continue;
			}
			
			// 1.4.3
			if(checkField_inserted('ja_resumes', 'general_detail_section') && $version_list [$i]=='1.4.3'){
				$param->set ( $var, 1 );
				$data = $param->toString ();
				
				$sql = "Update #__ja_config Set data='$data' Where tab='others'";
				$db->setQuery ( $sql );
				$db->query ();
				continue;
			}
				
			if(checkField_inserted('ja_form_fields', 'subscription_section') && $version_list [$i]=='1.4.0'){
				$param->set ( $var, 1 );
				$data = $param->toString ();
				
				$sql = "Update #__ja_config Set data='$data' Where tab='others'";
				$db->setQuery ( $sql );
				$db->query ();
				continue;
			}
			elseif(checkField_inserted('ja_form_fields', 'zipcode') && $version_list [$i]=='1.3.3'){
				$param->set ( $var, 1 );
				$data = $param->toString ();
				
				$sql = "Update #__ja_config Set data='$data' Where tab='others'";
				$db->setQuery ( $sql );
				$db->query ();
				continue;
			}
			
			if( checkUniqueField("currency", "ja_jobs") && $version_list [$i]=='1.4.7'){
				$param->set ( $var, 1 );
				$data = $param->toString ();
				$sql = "Update #__ja_config Set data='$data' Where tab='others'";
				$db->setQuery ( $sql );
				$db->query ();
				continue;
			}
			
			if( checkField_inserted('expiry_date', 'ja_jobs') && $version_list [$i]=='1.5.0'){
				$param->set ( $var, 1 );
				$data = $param->toString ();
				$sql = "Update #__ja_config Set data='$data' Where tab='others'";
				$db->setQuery ( $sql );
				$db->query ();
				continue;
			}
			
			$upgrade_path = JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_jajobboard' . DS . 'installer' . DS . 'sql' . DS . $filename . '.sql';
			if (file_exists ( $upgrade_path )) {
				populateDB ( $upgrade_path, $db, $error );
				if ($error) {
					$error = implode ( "<br/>", $error );
					return JError::raiseError ( 1, $error );
				} else {
					
					$param->set ( $var, 1 );
					$data = $param->toString ();
					
					$sql = "Update #__ja_config Set data='$data' Where tab='others'";
					$db->setQuery ( $sql );
					$db->query ();
				}
			} else {
				//				JError::raiseWarning(1, $filename.".sql ".JText::_('file not found.'));
			//				$err_msg .= $filename.".sql ".JText::_('file not found.').'<br />';
			}
		}
		if ($err_msg != '') {
			$err_msg .= '<br />' . JText::_ ( 'Upgrade data failed.' );
			JError::raiseWarning ( 1, $err_msg );
			//			echo $err_msg;
		} else {
			$sql = "UPDATE #__ja_paymentconfig SET published=0 WHERE name!='paypal'";
			$db->setQuery ( $sql );
			$db->query ();
		}
	}

}

	function checkUniqueField($field, $table){
		$db =& JFactory::getDBO();
		$db->setQuery("SELECT * FROM #__ja_form_fields WHERE field_name = '".$field."' AND table_name  = '".$table."'");
		$result = $db->loadObject();
		return $result;
	}

function standardize_keyword($keyword) {
	$keyword = trim ( $keyword );
	if (substr ( $keyword, 0, 1 ) == '"' && substr ( $keyword, count ( $keyword ) - 2, 1 ) == '"')
		$keyword = str_ireplace ( '" ', '"+', $keyword );
	
	$keyword = explode ( "+", $keyword );
	
	$temp_keyword = array ();
	
	for($i = 0; $i < count ( $keyword ); $i ++) {
		$keyword [$i] = trim ( $keyword [$i] );
		if (substr ( $keyword [$i], 0, 1 ) == '"' && substr ( $keyword [$i], count ( $keyword [$i] ) - 2, 1 ) == '"') {
			
			$keyword [$i] = substr ( $keyword [$i], 1, count ( $keyword [$i] ) - 2 );
		
		} elseif ($keyword [$i] != '') {
			$temp_keyword [] = explode ( ' ', $keyword [$i] );
			unset ( $keyword [$i] );
		}
	}
	for($i = 0; $i < count ( $temp_keyword ); $i ++)
		for($j = 0; $j < count ( $temp_keyword [$i] ); $j ++)
			if (trim ( $temp_keyword [$i] [$j] ) != '' && trim ( $temp_keyword [$i] [$j] ) != '+')
				$keyword [] = $temp_keyword [$i] [$j];
		//			$keyword = implode(' ',$keyword);
	

	return $keyword;
}

function findJobalert($job, $job_category, $job_location) {
	$jobalert_list = array ();
	$db = JFactory::getDBO ();
	$query = "SELECT r.* FROM #__ja_jobalerts AS r WHERE r.sendmail_duration!=0";
	$db->setQuery ( $query );
	$result_list = $db->loadObjectList ();
	
	if (count ( $result_list ) > 0) {
		$arr_job_category = explode ( ',', $job_category );
		
		for($i = 0; $i < count ( $result_list ); $i ++) {
			$check = true;
			//Check job type
			if ($job->job_type && $result_list [$i]->job_type)
				if ($job->job_type != $result_list [$i]->job_type)
					$check = false;
			//Check posted date
			if ($result_list [$i]->posted_date) {
				if ($result_list [$i]->lastest_checked == '0000-00-00 00:00:00')
					$result_list [$i]->lastest_checked = null;
				if ($result_list [$i]->lastest_checked) {
					$sendmail_time = strtotime ( $result_list [$i]->lastest_checked ) + $result_list [$i]->sendmail_duration * 86400;
				} else
					$sendmail_time = strtotime ( date ( 'Y-m-d H:i:s' ) ) + 86400;
				$filter_time = strtotime ( $job->effected_date ) + $result_list [$i]->posted_date * 86400;
				if ($filter_time < $sendmail_time)
					$check = false;
			}
			
			//Check category
			$result_list [$i]->category = explode ( ',', $result_list [$i]->category );
			$result_list [$i]->location = explode ( ',', $result_list [$i]->location );
			if (count ( array_diff ( $arr_job_category, $result_list [$i]->category ) ) == count ( $arr_job_category ) && ($job_category != ''))
				$check = false;
			
			//Check location
			//				if ($job_location!=$result_list[$i]->location&&$job_location!='')
			if (! in_array ( $job_location, $result_list [$i]->location ) && $job_location != '')
				$check = false;
			
			//Check keyword search
			if ( $result_list [$i]->keyword )
				switch ($result_list [$i]->keyword_option) {
					case 1 :
						$tem_keyword = explode ( ' ', $result_list [$i]->keyword_option );
												
						for($j = 0; $j < count ( $tem_keyword ); $j ++)
							if ($tem_keyword [$j] == '')
								unset ( $tem_keyword [$j] );
						$result_keyword = false;
						
						for($j = 0; $j < count ( $tem_keyword ); $j ++)
							if ( strpos ( $job->title, $result_list [$i]->keyword ) !== false || strpos ( $job->job_detail, $result_list [$i]->keyword )  !== false ) {
								$result_keyword = true;
								break;
							}
						if (! $result_keyword)
							$check = false;
						break;
					case 2 :
						$tem_keyword = explode ( ' ', $result_list [$i]->keyword_option );
						for($j = 0; $j < count ( $tem_keyword ); $j ++)
							if ($tem_keyword [$j] == '')
								unset ( $tem_keyword [$j] );
						$result_keyword = true;
						for($j = 0; $j < count ( $tem_keyword ); $j ++)
							if (! (stripos ( $job->title, $result_list [$i]->keyword ) !== false) && ! (stripos ( $job->job_detail, $result_list [$i]->keyword )  !== false) ) {
								$result_keyword = false;
								break;
							}
						if (! $result_keyword)
							$check = false;
						break;
					case 3 :
						if (! is_numeric ( (stripos ( $job->title, $result_list [$i]->keyword ) !== false) ) && ! is_numeric ( (stripos ( $job->job_detail, $result_list [$i]->keyword ) !== false) ))
							$check = false;
						break;
				}
			if ($check)
				$jobalert_list [] = $result_list [$i]->id;
		}
	}
	
	return $jobalert_list;
}

function findJobseeker() {
	$user_list = array ();
	$db = JFactory::getDBO ();
	$query = "SELECT * FROM #__ja_jobalerts WHERE sendmail_duration != 0 ";
	$db->setQuery ( $query );
	$result = $db->loadObjectList ();
	$count = 0;
	for($i = 0; $i < count ( $result ); $i ++) {
		$lastest_checked = $result [$i]->lastest_checked ? strtotime ( $result [$i]->lastest_checked ) : 0;
		if ( ( time() - $lastest_checked >= $result [$i]->sendmail_duration * 86400) && ($result [$i]->job_ids) ) {
			$user_list [$count] = new stdClass ( );
			//				$user_list[$result[$i]->user_id] = $user_list[$result[$i]->user_id]?$user_list[$result[$i]->user_id].",".$result[$i]->job_ids:$result[$i]->job_ids;
			$user_list [$count]->user_id = $result [$i]->user_id;
			$user_list [$count]->job_ids = $result [$i]->job_ids;
			$user_list [$count]->jobalert_id = $result [$i]->id;
			// Delete job list in job alert - begin - 
			$query = "UPDATE #__ja_jobalerts SET job_ids='',lastest_checked='" . date ( "Y-m-d H:i:s" ) . "' WHERE id=" . $result [$i]->id;
			
			$db->setQuery ( $query );
			$count ++;
			$db->query ();
			//Delete job list in job alert - end -
		}
	}
	
	return $user_list;
}

function auto_send_mail_to_jobseeker_about_job($is_completed) {
	global $jbconfig;
	$db = JFactory::getDBO ();
	$log_mark = array ('is_completed', 'lastest_sendmail', 'previous_sendmail' );
	if ($is_completed == 'new') {
		$user_list = findJobseeker ();
	} else {
		if ( time() - strtotime ( $jbconfig ['jobalert_log']->get ( 'previous_sendmail' ) ) <= 0)
			return;
		$user_list = $jbconfig ['jobalert_log']->toArray ();
		$temp_user_list = array ();
		
		foreach ( $user_list as $key => $value )
			if ($key != 'is_completed' && $key != 'previous_sendmail') {
				$temp = explode ( '_', $key );
				$temp_user_list [$temp [0]] = new stdClass ( );
				$temp_user_list [$temp [0]]->user_id = $user_list [$temp [0] . "_1"];
				$temp_user_list [$temp [0]]->job_ids = $user_list [$temp [0] . "_2"];
				$temp_user_list [$temp [0]]->jobalert_id = $user_list [$temp [0] . "_3"];
			}
		$user_list = $temp_user_list;
	}
	
	$arr_link = array ();
	$limit_sendmail = count ( $user_list ) > 100 ? 100 : count ( $user_list );
	$count = 0;
	if (is_array ( $user_list )) {
		foreach ( $user_list as $user_id => $job_ids ) {
			if ( ($job_ids == '') || ($job_ids == null) || ($user_id != 0 && in_array ( $user_id, $log_mark ))) {
				unset ( $user_list [$user_id] );
				continue;
			}
		}
		
		// die( print_r($user_list) );
		
		foreach ( $user_list as $key => $user ) {
			if (! $user->jobalert_id)
				continue;
			if ((! in_array ( $key, $log_mark ) && $key != 0) || $key == 0) {
				$arr_link ['ja_jobs'] = $user->job_ids;
				$arr_link['ja_jobs']['list'] = true;
				$arr_link ['users'] = $user->user_id;
				$arr_link ['ja_jobalerts'] = $user->jobalert_id;
				$mail = get_EmailTemplate ( $arr_link, 'SendMailToJobSeekerAboutJob' );
				$mail_user = JFactory::getUser ( $user->user_id );
				if (getUserType ( $user->user_id ) != JBJOB_SEEKER_USER)
					continue;
				
				if ($mail) {
					
					$result = sendMail ( $mail_user->email, $mail_user->name, $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName );
					
					if ($result)
						unset ( $user_list [$key] );
					
				} else {
					JError::raiseWarning ( 0, JText::_ ( 'Email template system was not found! Please contact Administrator!!' ) );
					//			    		return false;      
				}
				// unset ( $user_list [$key] );
				$count ++;
			}
			
			if ($count == $limit_sendmail)
				break;
		}
	}
	$param = '';
		
	if (count ( $user_list ) > 0) {
		foreach ( $user_list as $i => $job_ids ) //			for ($i=0;$i<count($user_list);$i++)
		{
			
			$param .= $i . "_1=" . $user_list [$i]->user_id . "\n";
			$param .= $i . "_2=" . $user_list [$i]->job_ids . "\n";
			$param .= $i . "_3=" . $user_list [$i]->jobalert_id . "\n";
		}
		$param .= "is_completed=running \nprevious_sendmail=" . date ( "Y-m-d H:i:s" );
	} else
		$param .= "lastest_sendmail=" . date ( "Y-m-d" );
	
	$query = "UPDATE #__ja_config SET data='" . $param . "' WHERE tab='jobalert_log'";
	
	$db->setQuery ( $query );
	$db->query ();

}

function auto_check_jobalert_about_job($job, $diff_cat = '', $diff_location = '') {
	$db = JFactory::getDBO ();
	$jobalert_list = findJobalert ( $job, $diff_cat, $diff_location );
	
	for($i = 0; $i < count ( $jobalert_list ); $i ++) {
		$query = "SELECT * FROM #__ja_jobalerts WHERE id = " . ( int ) $jobalert_list [$i];
		$db->setQuery ( $query );
		$job_alert = $db->loadObject ();
		$list_job = $job_alert->job_ids ? $job_alert->job_ids . "," . $job->id : $job->id;
		$query = "UPDATE #__ja_jobalerts SET job_ids='$list_job' WHERE id=$jobalert_list[$i]";
		$db->setQuery ( $query );
		$db->query ();
	}
}

function findJobForJobAlert($jobalert) {
	require_once (JPATH_COMPONENT . DS . "models" . DS . "jajobs.php");
	$job_model = new JobBoardModelJAJobs ( );
	/*$job_list = $job_model->getItems ( '', 99999999, 1 );
	$str_job_list = '';
	$jobalert->category = explode ( ',', $jobalert->category );
	$jobalert->location = explode ( ',', $jobalert->location );
	for($i = 0; $i < count ( $job_list ); $i ++) { //var_dump($job_list[$i]->id);
		$check = true;
		//Check job type
		if ($job_list [$i]->job_type && $jobalert->job_type)
			if ($job_list [$i]->job_type != $jobalert->job_type)
				$check = false;
			//			var_dump($check);
		//Check posted date
		/*if ($jobalert->posted_date) {
			if ($jobalert->lastest_checked == '0000-00-00 00:00:00')
				$jobalert->lastest_checked = null;
			if ($jobalert->lastest_checked) {
				$sendmail_time = strtotime ( $jobalert->lastest_checked ) + $jobalert->sendmail_duration * 86400;
			} else
				$sendmail_time = strtotime ( date ( 'Y-m-d H:i:s' ) ) + 86400;
			$filter_time = strtotime ( $job_list [$i]->effected_date ) + $jobalert->posted_date * 86400;
			if ($filter_time < $sendmail_time)
				$check = false;
		}
		//			var_dump($check);
		//Check category
		

		if (! is_array ( $job_list [$i]->cat_id ))
			$arr_job_category = explode ( ',', $job_list [$i]->cat_id );
		else
			$arr_job_category = $job_list [$i]->cat_id;
		
		if (count ( array_diff ( $arr_job_category, $jobalert->category ) ) == count ( $arr_job_category ) && (count ( $jobalert->category ) > 0))
			$check = false;
			//				var_dump($check);
		$temp = getItemByFieldName ( 'ja_location', 'name', "'" . $job_list [$i]->location_id . "'" );
		$job_list [$i]->location_id = $temp [0]->id;
		//Check location
		//				if ($job_location!=$jobalert->location&&$job_location!='')
		if (! in_array ( $job_list [$i]->location_id, $jobalert->location ) && count ( $jobalert->location ) > 0)
			$check = false;
			//			var_dump($check);
		//Check keyword search
		if ($jobalert->keyword)
			switch ($jobalert->keyword_option) {
				case 1 :
					$tem_keyword = explode ( ' ', $jobalert->keyword_option );
					for($j = 0; $j < count ( $tem_keyword ); $j ++)
						if ($tem_keyword [$j] == '')
							unset ( $tem_keyword [$j] );
					$result_keyword = false;
					for($j = 0; $j < count ( $tem_keyword ); $j ++)
						if (stripos ( $job_list [$i]->title, $tem_keyword [$j] ) || stripos ( $job_list [$i]->job_detail, $tem_keyword [$j] )) {
							$result_keyword = true;
							break;
						}
					if (! $result_keyword)
						$check = false;
					break;
				case 2 :
					$tem_keyword = explode ( ' ', $jobalert->keyword_option );
					for($j = 0; $j < count ( $tem_keyword ); $j ++)
						if ($tem_keyword [$j] == '')
							unset ( $tem_keyword [$j] );
					$result_keyword = true;
					for($j = 0; $j < count ( $tem_keyword ); $j ++)
						if (! stripos ( $job_list [$i]->title, $tem_keyword [$j] ) && ! stripos ( $job_list [$i]->job_detail, $tem_keyword [$j] )) {
							$result_keyword = false;
							break;
						}
					if (! $result_keyword)
						$check = false;
					break;
				case 3 :
					if (! is_numeric ( stripos ( $job_list [$i]->title, $jobalert->keyword ) ) && ! is_numeric ( stripos ( $job_list [$i]->job_detail, $jobalert->keyword ) ))
						$check = false;
					break;
			}
		if ($check)
			$str_job_list = $str_job_list ? $str_job_list . ',' . $job_list [$i]->id : $job_list [$i]->id;
	}
	if ($str_job_list) {
		$db = JFactory::getDBO ();
		$query = "UPDATE #__ja_jobalerts SET job_ids='$str_job_list' WHERE id=$jobalert->id";
		$db->setQuery ( $query );
		$db->query ();
	}
	*/
	
	$post	= JRequest::get('post');
	$jobModel	= new JobBoardModelJAJobs ( );
	JRequest::setVar("limit", 1000);
	JRequest::setVar("limitstart", 0);
	foreach ($post as $k=>$v){
		if($k != 'cid'){
			JRequest::setVar($k, '');
		}
	}
	$jobs = $jobModel->show_result_jobalert();
	$job_ids = array();
	if($jobs){
		foreach ($jobs as $job){
			$job_ids[] = $job->id;
		}
	}
	$job_ids = implode(",", $job_ids);
	$db = JFactory::getDBO();
	$db->setQuery("UPDATE #__ja_jobalerts SET job_ids = '".$job_ids."', lastest_checked = '0000:00:00' WHERE id = ".$jobalert->id);
	$db->query();
	
	$db->setQuery("UPDATE #__ja_config SET data = '0000:00:00' WHERE tab = 'jobalert_log' ");
	$db->query();
}

function jaJBResize($image, $max_width, $max_height) {
	$path = JPATH_SITE;
	$imgInfo = getimagesize ( $path . '/' . $image );
	$width = $imgInfo [0];
	$height = $imgInfo [1];
	if (! $max_width && ! $max_height) {
		$max_width = $width;
		$max_height = $height;
	} else {
		if (! $max_width)
			$max_width = 1000;
		if (! $max_height)
			$max_height = 1000;
	}
	$x_ratio = $max_width / $width;
	$y_ratio = $max_height / $height;
	if (($width <= $max_width) && ($height <= $max_height)) {
		$tn_width = $width;
		$tn_height = $height;
	} else if (($x_ratio * $height) < $max_height) {
		$tn_height = ceil ( $x_ratio * $height );
		$tn_width = $max_width;
	} else {
		$tn_width = ceil ( $y_ratio * $width );
		$tn_height = $max_height;
	}
	
	$ext = strtolower ( substr ( strrchr ( $image, '.' ), 1 ) ); // get the file extension
	$rzname = strtolower ( substr ( $image, 0, strpos ( $image, '.', strlen ( $image ) - 5 ) ) ) . "_{$tn_width}_{$tn_height}.{$ext}"; // get the file extension
	$resized = $path . '/' . $rzname;
	if (file_exists ( $resized )) {
		$smallImg = getimagesize ( $resized );
		if (($smallImg [0] <= $tn_width && $smallImg [1] == $tn_height) || ($smallImg [1] <= $tn_height && $smallImg [0] == $tn_width)) {
			return $rzname;
		}
	}
	
	switch ($imgInfo [2]) {
		case 1 :
			$im = imagecreatefromgif ( $path . '/' . $image );
			break;
		case 2 :
			$im = imagecreatefromjpeg ( $path . '/' . $image );
			break;
		case 3 :
			$im = imagecreatefrompng ( $path . '/' . $image );
			break;
		default :
			return '';
			break;
	}
	
	$newImg = imagecreatetruecolor ( $tn_width, $tn_height );
	
	/* Check if this image is PNG or GIF, then set if Transparent*/
	if (($imgInfo [2] == 1) or ($imgInfo [2] == 3)) {
		imagealphablending ( $newImg, false );
		imagesavealpha ( $newImg, true );
		$transparent = imagecolorallocatealpha ( $newImg, 255, 255, 255, 127 );
		imagefilledrectangle ( $newImg, 0, 0, $tn_width, $tn_height, $transparent );
	}
	imagecopyresampled ( $newImg, $im, 0, 0, 0, 0, $tn_width, $tn_height, $imgInfo [0], $imgInfo [1] );
	
	//Generate the file, and rename it to $newfilename
	switch ($imgInfo [2]) {
		case 1 :
			imagegif ( $newImg, $resized );
			break;
		case 2 :
			imagejpeg ( $newImg, $resized, 90 );
			break;
		case 3 :
			imagepng ( $newImg, $resized );
			break;
		default :
			return '';
			break;
	}
	
	if( file_exists(JPATH_SITE.DS.$rzname) )
		return $rzname;
	else return $image;

}
function show_full_location_tree($location_id, $init = '') { //var_dump($init);
	$db = JFactory::getDBO ();
	$query = "SELECT * FROM #__ja_location WHERE id=" . ( int ) $location_id;
	$db->setQuery ( $query );
	$location = $db->loadObject ();
	if ($init)
		$result = $init;
	else
		$result = array ();
	if ($location) {
		$result [] = $location->name;
		if ($location->parent_id)
			$result = show_full_location_tree ( $location->parent_id, $result );
	}
	
	return $result;
}

function getCurrencySymbol() {
	global $jbconfig;
	if ($jbconfig ['currency']->get ( 'mode' ) != 'real_currency')
		$currency = $jbconfig ['currency']->get ( 'currency_symbol' );
	else
		$currency = $jbconfig ['currency']->get ( 'currency' );
	return $currency;
}
function getCurrency() {
	global $jbconfig;
	if ($jbconfig ['currency']->get ( 'mode' ) != 'real_currency')
		$currency = $jbconfig ['currency']->get ( 'currency_name' );
	else
		$currency = $jbconfig ['currency']->get ( 'currency_code' );
	return $currency;
}
function remove_attach($table_name) {
	$db = JFactory::getDBO ();
	$field_name = JRequest::getVar ( 'field_name' );
	$item_id = JRequest::getVar ( 'item_id' );
	$query = "UPDATE #__$table_name SET $field_name='' WHERE id=$item_id";
	$db->setQuery ( $query );
	if ($db->query ())
		echo $field_name;
	else
		echo '';
}

function getItemNotes($where) {
	$db = JFactory::getDBO ();
	$query = "SELECT * FROM #__ja_notes WHERE 1=1$where";
	$db->setQuery ( $query );
	$note_list = $db->loadObjectList ();
	$temp = array ();
	if (count ( $note_list ) > 0) {
		for($i = 0; $i < count ( $note_list ); $i ++)
			$temp [$note_list [$i]->item_id] = $note_list [$i];
		$note_list = $temp;
		return $note_list;
	}
	return '';
}

function build_relation_value_JS() {
	$db = JFactory::getDBO ();
	//Build location
	$query = "SELECT * FROM #__ja_location WHERE published=1";
	$db->setQuery ( $query );
	$result = $db->loadObjectList ();
	child_JS ( $result, 'location_id' );
	
	//Build category
	$query = "SELECT * FROM #__ja_categories WHERE published=1";
	$db->setQuery ( $query );
	$result = $db->loadObjectList ();
	child_JS ( $result, 'cat_id' );

}
function child_JS($items, $field_name) {
	echo '<script type="text/javascript" language="javascript">';
	//    	echo '// <![CDATA[  ';
	echo 'var child_' . $field_name . ' = new Array();';
	
	for($i = 0; $i < count ( $items ); $i ++)
		if ($items [$i]->parent_id) {
			echo 'var parent_id = ' . $items [$i]->parent_id . ';';
			echo 'if (!child_' . $field_name . '[parent_id]) child_' . $field_name . '[parent_id] = new Array();';
			echo 'child_' . $field_name . '[parent_id][child_' . $field_name . '[parent_id].length + 1] =' . $items [$i]->id . '; ';
		}
		
	//    	echo '// ]]> ';
	echo '</script>';
	?>
<script type="text/javascript" language="javascript">
// <![CDATA[
function child_selection(obj,obj_option)
{
	var inc_array = new Array(obj_option.value);
	
if (obj_option.selected)	
	for (i=0;i<obj.options.length;i++)
	if (in_array(obj.options[i].value,inc_array))
	{
		if (obj.options[i].selected)
		{
			if (obj.id=='location_id')
			{
				if (child_location_id[obj.options[i].value])	
					for (k=0;k<child_location_id[obj.options[i].value].length;k++)
						for (ii=i+1;ii<obj.options.length;ii++)
							if (obj.options[ii].value==child_location_id[obj.options[i].value][k])
							{
								obj.options[ii].selected = true;
								inc_array[inc_array.length] = obj.options[ii].value;
							}
			}
			else
			{
				if (child_cat_id[obj.options[i].value])	
					for (k=0;k<child_cat_id[obj.options[i].value].length;k++)
						for (ii=i+1;ii<obj.options.length;ii++)
							if (obj.options[ii].value==child_cat_id[obj.options[i].value][k])
							{
								obj.options[ii].selected = true;
								inc_array[inc_array.length] = obj.options[ii].value;
							}
			}
		}
	}

}
function in_array(ele, inc_array)
{
	for (x in inc_array)
		if (inc_array[x]==ele)
			return true;
	return false;	
}
function cal_number_selection(field_name,child_array)
{
	sum_selection = 0;
	obj = document.getElementById(field_name);
	if (obj)
	for (i=0;i<obj.options.length;i++)
	{
		if (!check_exist_child(child_array,obj.options[i].value)&&obj.options[i].selected)
			sum_selection++;
	}
	return sum_selection;
	
}
function check_exist_child (child_array,ele)
{
	if (child_array[ele])
		return true;
	else
		return false;
}
// ]]>
</script>
<?php
}
function change_upload_folder() {
	global $jbconfig;
	$source = 'components' . DS . 'com_jajobboard' . DS . 'uploads';
	$upload_folder = isset ( $jbconfig ['general'] ) ? $jbconfig ['general']->get ( 'upload_folder', DS . 'images' . DS . 'stories' . DS . 'jbuploads' ) : DS . 'images' . DS . 'stories' . DS . 'jbuploads';
	$destination = substr ( JPATH_SITE . $upload_folder, 1 );
	//Move all file
	if (! JFolder::exists ( JPATH_SITE . DS . $destination ) && JFolder::exists ( JPATH_SITE . DS . $source )) {
		JFolder::copy ( JPATH_SITE . DS . $source, JPATH_SITE . DS . $destination );
		JFolder::delete ( JPATH_SITE . DS . $source );
	}
	
	//Change database
	$source = str_replace ( DS, '/', $source );
	$destination = str_replace ( DS, '/', $destination );
	$db = JFactory::getDBO ();
	$query = "SELECT * FROM #__ja_form_fields WHERE field_type='IMAGE' or field_type='FILE'";
	$db->setQuery ( $query );
	$field_list = $db->loadObjectList ();
	for($i = 0; $i < count ( $field_list ); $i ++) {
		$query = "SELECT * FROM #__" . $field_list [$i]->table_name;
		$db->setQuery ( $query );
		$item_list = $db->loadObjectList ();
		for($k = 0; $k < count ( $item_list ); $k ++) {
			$value = $item_list [$k]->{$field_list [$i]->field_name};
			$value = str_replace ( $source, $destination, $value );
			$query = "UPDATE #__" . $field_list [$i]->table_name . " SET " . $field_list [$i]->field_name . "='$value' WHERE id=" . $item_list [$k]->id;
			$db->setQuery ( $query );
			$db->query ();
		}
	}

}
function check_search_resume_package() {
	$user = JFactory::getUser ();
	if ($user->id) {
		$now = date ( 'Y-m-d H:i:s' );
		$now = strtotime ( $now );
		$emp_acc = getItemByFieldName ( 'ja_employers', 'user_id', $user->id );
		if ($emp_acc) {
			$emp_acc = $emp_acc [0];
			if ($emp_acc->begin_date_search_resume)
				$begin_search = strtotime ( $emp_acc->begin_date_search_resume );
			else 
				$begin_search = '';
			if ($emp_acc->end_date_search_resume)
				$end_search = strtotime ( $emp_acc->end_date_search_resume );
			else 	
				$end_search = '';
			if ($now < $begin_search || $now > $end_search)
				return false;
			else
				return true;
		} else
			return false;
	} else
		return false;
}

function jaGetImageSize($path) {
	
	if( strpos($path, JURI::base() ) !== false )
		$path = str_replace(JURI::base(), JPATH_SITE.DS, $path);
	
	if ( strpos ( $path, JPATH_SITE ) === false )
		$path = JPATH_SITE . DS . $path;
			
	$temp_path = str_replace ( '\\', DS, $path );
	$temp_path = str_replace ( '/', DS, $path );
	if (file_exists ( $temp_path )) {
		$imgInfo = getimagesize ( $temp_path );
		$image_size ['width'] = $imgInfo [0];
		$image_size ['height'] = $imgInfo [1];
		return $image_size;
	} else
		return null;
}

function getSearchFieldList($table_name) {
	$db = JFactory::getDBO ();
	$query = "SELECT * FROM #__ja_searchforms WHERE table_name='" . $table_name . "'";
	$db->setQuery ( $query );
	$result = $db->loadObjectList ();
	return $result;
}

function autoSendmailForEmployer() {
	global $jbconfig;
	$last_sendmail_employer = $jbconfig['others']->get('last_sendmail_employer','0');
	if ((strtotime(date ( 'Y-m-d H:i:s' ))-strtotime($last_sendmail_employer))/24/60/60<1)
		return;
	$db = JFactory::getDBO ();
	$query = "SELECT id,user_id,change_log,DATEDIFF(curdate(),latest_sendmail) AS sent_day,duration_notice FROM #__ja_profiles WHERE modified_notice=1 and ((DATEDIFF(curdate(),latest_sendmail)>duration_notice) or (DATEDIFF(curdate(),latest_sendmail)=null)) and (change_log<>null) and (change_log<>'')";
	$db->setQuery ( $query );
	$result = $db->loadObjectList ();
	$arr_user_id = array ();
	for($i = 0; $i < count ( $result ); $i ++)
//		if (((( int ) $result [$i]->sent_day > ( int ) $result [$i]->duration_notice) || ($result [$i]->sent_day == null)) && ($result [$i]->change_log != null) && ($result [$i]->change_log != '')) 
		{
			$arr_user_id [] = $result [$i]->user_id;
			
			$arr_link = array ();
			$arr_link ['users'] = $result [$i]->user_id;
			$arr_link ['ja_profiles'] = $result [$i]->id;
			$mail = get_EmailTemplate ( $arr_link, 'sendmail_to_employer_update_job' );
			if ($mail) {
				$user = JFactory::getUser ( $result [$i]->user_id );
				sendMail ( $user->email, $user->name, $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName );
			}
		}
	if (count ( $arr_user_id ) > 0) {
		$query = "UPDATE #__ja_profiles SET change_log='',latest_sendmail='" . date ( 'Y-m-d' ) . "' WHERE user_id IN (" . implode ( ',', $arr_user_id ) . ")";
		$db->setQuery ( $query );
		$db->query ();
		
	}
	$data = isset ( $jbconfig ['others'] ) ? $jbconfig ['others']->toString () : '';
	$data = substr($data,0,strpos($data,'last_sendmail_employer')-1);
	$query = "UPDATE #__ja_config SET data='" . $data . "\nlast_sendmail_employer=" . date ( 'Y-m-d H:i:s' ) ."' WHERE tab='others'";
	$db->setQuery ( $query );
	$db->query ();

}

function assign_editor_field(&$row) {
	for($i = 0; $i < count ( $row->editor_field ); $i ++) {
		if ($row->editor_field [$i]) {
			if (JRequest::getVar('task')=='save_application'){
				$row->{$row->editor_field [$i]} = JRequest::getVar ( $row->editor_field [$i].$row->job_id, '', 'post', 'string', JREQUEST_ALLOWRAW );
				$row->{$row->editor_field [$i]} = str_replace("\n", "<br/>", $row->{$row->editor_field [$i]});
			}else 
				$row->{$row->editor_field [$i]} = JRequest::getVar ( $row->editor_field [$i], '', 'post', 'string', JREQUEST_ALLOWRAW );
		}
	}
	return $row;
}

function clearDataForJobSeeker($user_id) {
	$db = JFactory::getDBO ();
	
	// Check ShortList
	

	//Favourite job for job seeker + Favourite resume of employer
	$query = "DELETE FROM #__ja_shortlist WHERE (user_id=" . ( int ) $user_id . ") OR  (item_id=" . ( int ) $user_id . " AND listtype='ja_resumes')";
	$db->setQuery ( $query );
	$db->query ();
	
	//Check Job alerts
	$query = "DELETE FROM #__ja_jobalerts WHERE user_id=" . ( int ) $user_id;
	$db->setQuery ( $query );
	$db->query ();
	
	//Check application
	$query = "DELETE FROM #__ja_applications WHERE user_id=" . ( int ) $user_id;
	$db->setQuery ( $query );
	$db->query ();
	
	//Check job notes
	$query = "DELETE FROM #__ja_notes WHERE user_id=" . ( int ) $user_id;
	$db->setQuery ( $query );
	$db->query ();
}

function clearDataForEmployer($user_id) {
	$db = JFactory::getDBO ();
	//Check ShortList
	$query = "DELETE FROM #__ja_shortlist WHERE (user_id=" . ( int ) $user_id . ")";
	$db->setQuery ( $query );
	$db->query ();
	
	//Check resume notes
	$query = "DELETE FROM #__ja_notes WHERE user_id=" . ( int ) $user_id;
	$db->setQuery ( $query );
	$db->query ();
	
	//Check application for job
	$query = "SELECT id FROM #__ja_jobs WHERE user_id=" . ( int ) $user_id;
	$db->setQuery ( $query );
	$job_list = $db->loadObjectList ();
	$temp_job_list = array ();
	for($i = 0; $i < count ( $job_list ); $i ++) {
		$temp_job_list [] = $job_list [$i]->id;
	}
	if (count ( $temp_job_list ) > 0) {
		//Delete application of jobs
		$str_job_list = implode ( ',', $temp_job_list );
		$query = "DELETE FROM #__ja_applications WHERE job_id IN ($str_job_list)";
		$db->setQuery ( $query );
		$db->query ();
		
		//Delete job in shortlist
		$query = "DELETE FROM #__ja_shortlist WHERE item_id IN ($str_job_list) AND listtype='ja_jobs'";
		$db->setQuery ( $query );
		$db->query ();
		
		//Delete note
		$query = "DELETE FROM #__ja_notes WHERE item_id IN ($str_job_list) AND listtype='ja_jobs'";
		$db->setQuery ( $query );
		$db->query ();
	
	}
	
	//Delete all jobs
	$query = "DELETE FROM #__ja_jobs WHERE user_id=" . ( int ) $user_id;
	$db->setQuery ( $query );
	$db->query ();

}

function filterItemListViaFieldName($items, $field_name, $filter_value) {
	global $jbconfig;
	//	$filter_value = JRequest::getVar($field_name);
	$temp_items = array ();
	for($i = 0; $i < count ( $items ); $i ++) {
		$item = $items [$i];
//		var_dump($item->{$field_name});
		if (!is_array ( $item->{$field_name} ))
			$temp_value = explode ( ',', $item->{$field_name} );
		else
			$temp_value = $item->{$field_name};
		
//		if ($field_name == 'location_id_tmp')
//			$temp_value = getLocation ( $temp_value );
//		else
//			$temp_value = getCategories ( $temp_value );
			
		//Filter via text
		if (count( array_intersect( $temp_value, $filter_value ) )>0) {
			$temp_items [] = $items [$i];
		}
	
	}
	return $temp_items;
}

function get_Itemid($find = array()) {
	
	if ( ! class_exists("JSite") )
		require_once( JPATH_ADMINISTRATOR.DS."components".DS."com_search".DS."helpers".DS."site.php" );
	
	$menus = & JSite::getMenu ();
	$Itemid = 9999;
	foreach ( $menus->_items as $row ) {
		
		if( ! isset($find ['option']) ) $find ['option'] = "";
		if( ! isset($row->query ['option']) ) $row->query ['option'] = "";	
		
		if ($row->query ['option'] == $find ['option'] && $row->query ['view'] == $find ['view'] && (! isset ( $row->query ['layout'] ) || ! isset ( $find ['layout'] ) || (isset ( $row->query ['layout'] ) && isset ( $find ['layout'] ) && $row->query ['layout'] == $find ['layout']))) {
			$Itemid = $row->id;
			break;
		}
	}
	return $Itemid;
}
function checkMailConnect()
{
	global $jbconfig;
	$last_check_mail_connect = $jbconfig['emails']->get('last_check_mail_connect');
	$data = isset($jbconfig['others'])?$jbconfig['others']->toString():'';
	
	$mail = JFactory::getMailer();
	switch ($mail->Mailer)
	{
		case 'smtp':
			include_once('libraries/phpmailer/smtp.php');
			if (!$mail->SmtpConnect())
				return false;
			break;
		case 'sendmail':
			$sendmail = sprintf("%s -oi -t", escapeshellcmd($mail->Sendmail));
			if(!@$mail = popen($sendmail, 'w'))
				return false;
			break;
		default:
			break;
	}
	return true;
}

function getFullLocations($parent_id)
{
	$db = JFactory::getDBO();
	$query = "SELECT id FROM #__ja_location WHERE (id=$parent_id or parent_id=$parent_id) and published=1";
	$db->setQuery($query);
	$names = $db->loadResultArray ();
	return $names;
}

function getFullCategories($parent_id)
{
	$db = JFactory::getDBO();
	$query = "SELECT id FROM #__ja_categories WHERE (id=$parent_id or parent_id=$parent_id) and published=1";
	$db->setQuery($query);
	$names = $db->loadResultArray ();
	return $names;
}

function getTemplate() {
	static $template;
	
	if (! isset ( $template )) {
		// Load the template name from the database
		$db = & JFactory::getDBO ();
		$query = 'SELECT template' . ' FROM #__templates_menu' . ' WHERE client_id = 0' . ' AND menuid = 0';
		$db->setQuery ( $query );
		$template = $db->loadResult ();
		
		$template = JFilterInput::clean ( $template, 'cmd' );
		
		if (! file_exists ( JPATH_SITE . DS. 'templates'. DS . $template . DS . 'index.php' )) {
			$template = 'rhuk_milkyway';
		}
	}
	
	return $template;
}

/**
 * Enter description here...
 *
 */
function display_form_activate_step1() {
	?>
	<script type="text/javascript">
		function validate(){
			if($('key').value.trim()==''){
				alert('<?php echo JText::_ ( "Please enter your license key." )?>');
				$('key').focus();
				return false;
			}
			document.adminForm.disabled = true;
			return true;
		}		
	</script>
	<div style="width: 100%; text-align: center">
		<center>
		<form action="index.php" name="adminForm" method="post">
		<h3><?php echo JText::_('Welcome to the JA JobBoard!')?></h3>
		<fieldset style="width: 50%; text-align: center">	
			<legend><?php echo JText::_ ( "Activate code" )?></legend>
		    <table align="center" id="radio-box" width="100%">
				
				<tr id="license_key_box">
					<td align="left" style="margin-left: 20px">
						<label for="email"><?php echo JText::_ ( "Enter your License key" )?></label>
						<span class="buynow">[<a href="http://www.joomlart.com/member/signup.php?group=jajobboard"><?php echo JText::_ ( "Buy now" )?></a></span> &amp; 
						<br />
						<textarea rows="6" cols="80" name="key" id="key"></textarea>
		
					</td>
				</tr>
				<tr>
					<td align="left">
						<input type="hidden" name="option" value="com_jajobboard" /> 
						<input type="hidden" name="action" value="verify_license_key" /> 
						<input type="submit" name="submit"	onclick="return validate()"	value="<?php echo JText::_ ( "Next" )?>" />
					</td>
				</tr>
			</table>
		</fieldset>
		</form>
		</center>
	</div>
<?php
}


/**
 * Enter description here...
 *
 */
function verify_license_key() {
	global $mainframe;
	
	if (check_license_time ()){
		return;
	}
		
	$key = JRequest::getVar ( 'key', '');
	if(!$key){
		JError::raiseWarning(1, JText::_('Please enter your license key!'));
		display_form_activate_step1();
		return;
	}
	
	$domain = $_SERVER ['HTTP_HOST'];
	$base = $mainframe->getSiteUrl ();
	
	if (strtolower ( substr ( $domain, 0, 3 ) ) == 'www') {
		$domain = substr ( $domain, strpos ( $domain, '.' ) + 1 );
	}
	
	$req = 'domain=' . $domain;
	$req .= '&key=' . rawurlencode ( $key );
	$req .= '&base=' . rawurlencode ( $base );
	$req .= '&action=verify_license_key_new';
	$host = 'www.joomlart.com';
	$path = "/member/licence.php";
	$URL = "http://$host$path";

	if (! function_exists ( 'curl_version' )) {
		if (! ini_get ( 'allow_url_fopen' )) {
			JError::raiseWarning ( 1, JText::_ ( 'Sorry, but your server does not currently support open method. Please contact the network administrator system for help.' ) );
			return;
		} else {
			$result = socket_getdata ( $req );
		}
	} else {
		$result = curl_getdata ( $URL, $req );
	}
	
	if (! $result) { //Not connected to server
		$expire_time = strtotime(  date ( "Y-m-d" ) . " +3 days");
		JError::raiseWarning ( 1, sprintf(JText::_ ( 'Oops, we can not verify your license key at the moment.<br/>Make sure you are on good internet connection.<br/>Please verify it again within the next 3 days. You can still use the component until %s', date('Y-m-d H:i:s', $expire_time) )) );
		$msg = update_license_config($domain, $expire_time, 'N/A', 'Waiting verify');
   		if($msg){
   			$_SESSION[md5($_SERVER['HTTP_HOST'].'cheking')] = true;
   			return ;
   		}
   		else{
   			update_key_config('key', $key);
   			$mainframe->redirect('index.php?option=com_jajobboard');
   		}		
	} else {
		$data = explode ( '######', $result );
		$count = count($data);
		switch ($count) {
			case 1 :
				{
					display_form_activate_step1 ();
					JError::raiseWarning(1, $result);
					return;
				}
				break;
			
			default :
				{
					$data = explode ( '######', $result );
					$count = count ( $data );
					
					if ( in_array($count, array(4, 6 ,7)) ) {
						$expire_time = $data [1];
						
						if($expire_time<=time()){
							JError::raiseWarning(1, JText::_('Your license has expired. Therefore the system will be disabled. Please contact <a href="http://support.joomlart.com/">JoomlArt</a> for further assistance.'));
							display_form_activate_step1 ();
							return;
						}
							
						
						update_key_config ( 'key', $key );
						if (isset ( $data [0] ) && $data [0] != '') {
							$create_date = time();
							
							$accept_domains = $data [0];
							if(!in_array($domain, explode(',', $data [0]))) $data [0] = $domain;
							update_license_config ( $data [0], $expire_time, $data [2], '', $create_date );
						}
						
						if (isset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'JAJOBBOARD_UNVALID_LICENSE' )] )){
							unset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'JAJOBBOARD_UNVALID_LICENSE' )] );
						}
						if (isset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'cheking' )] )) {
							unset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'cheking' )] );
						}
						
						if (! defined ( 'AUTO_CHECKING' )) {
							if($count==6){
								show_trial_license_detail (false, $data[4], $accept_domains, $data[5]);
							}
							elseif($count==7 && $data[6]=='64e29da50435cfd7c2ccae48ffc33899'){
								show_trial_license_detail (true, $data[4], $accept_domains, $data[5]);
							}							
							else{
								show_license_detail ();
							}
						} else {
							$mainframe->redirect ( 'index.php?option=com_jajobboard' );
						}
						return;
						
					} else if (strpos ( $result, '(101) Network is unreachable' ) !== FALSE) {
						unset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'cheking' )] );
						$_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'JAJOBBOARD_CHECKED' )] = true;
						JError::raiseWarning ( 1, JText::_ ( '(101) Network is unreachable' ) );
						return $mainframe->redirect ( JURI::base () . 'index.php?option=com_jajobboard' );
					} else {
						JError::raiseWarning ( 1, JText::_ ( 'Your license key is not accepted. Please contact <a href="http://support.joomlart.com/">JoomlArt</a> for further assistance.') );
						display_form_activate_step1 ();
						return;
					}
				}
		}
	}
}

/**
 * Enter description here...
 *
 * @param unknown_type $key
 * @param unknown_type $action
 * @return unknown
 */
function verify_new_license_key($key = '', $action = true) {	
	global $mainframe;
	$db = JFactory::getDBO ();
	if (isset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'cheking' )] ))
		unset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'cheking' )] );
	
	$domain = $_SERVER ['HTTP_HOST'];
	$base = $mainframe->getSiteUrl ();
	
	if (! $key) {
		$sql = "select data from #__ja_config where tab in ('key')";
		$db->setQuery ( $sql );
		$key = $db->loadResult ();
	}
	
	if (! $key || ! $domain) {
		return FALSE;
	}
	
	if (strtolower ( substr ( $domain, 0, 3 ) ) == 'www') {
		$domain = substr ( $domain, strpos ( $domain, '.' ) + 1 );
	}
	
	$req = 'domain=' . $domain;
	$req .= '&key=' . rawurlencode ( $key );
	$req .= '&base=' . rawurlencode ( $base );
	$req .= '&action=verify_license_key_new';
	$host = 'www.joomlart.com';
	$path = "/member/licence.php";
	$URL = "http://$host$path";
	$msg = 'Unable to connect to the server by JoomlArt. Please check your internet connection.';
	
	if (! function_exists ( 'curl_version' ) ) {
		if (! ini_get ( 'allow_url_fopen' )) {
			JError::raiseWarning ( 1, JText::_ ( 'Your License Key could not be verified. Please check your internet connection and try again. Kindly try another method to continue' . '. <a href="http://joomlart.com">' . JText::_ ( 'Or contact JoomlArt for further assistance' ) . '.</a>' ) );
			return;
		} else {			
			$result = socket_getdata ( $host, $path, $req );
		}
	} else {
		$result = curl_getdata ( $URL, $req );
	}
	
	if (! $result) { //Not connected to server
		if ($action) {
			JError::raiseWarning ( 1, JText::_ ( $msg ) );
			return;
		} else {
			if (isset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'JAJOBBOARD_UNVALID_LICENSE' )] ))
				unset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'JAJOBBOARD_UNVALID_LICENSE' )] );
			if (isset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'cheking' )] )) {
				unset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'cheking' )] );
			}
			return true;
		}
	
	} else {
		$data = explode ( '######', $result );
		$count = count($data);
		switch ($count) {
			case 1 :
				{
					//display_form_activate_step1 ();
					JError::raiseWarning(1, $result);
					return;
				}
				break;						
			
			default :
				{
					$data = explode ( '######', $result );
					$count = count ( $data );
					
					if ( in_array($count, array(4, 6 ,7)) ) {
						update_key_config ( 'key', $key );
						
						if (isset ( $data [0] ) && $data [0] != '') {
							$create_date = time();
							$expire_time = $data [1];
							$accept_domains = $data [0];
							if(!in_array($domain, explode(',', $data [0]))) $data [0] = $domain;
							update_license_config ( $data [0], $expire_time, $data [2], '', $create_date );
						}
						
						if($expire_time>time()){
							if (isset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'JAJOBBOARD_UNVALID_LICENSE' )] )){
								unset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'JAJOBBOARD_UNVALID_LICENSE' )] );
							}
							if (isset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'cheking' )] )) {
								unset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'cheking' )] );
							}
							
							if($count==6 && $action){
								show_trial_license_detail (false, $data[4], $accept_domains, $data[5], false);
							}
							elseif($count==7 && $data[6]=='64e29da50435cfd7c2ccae48ffc33899'  && $action){
								show_trial_license_detail (true, $data[4], $accept_domains, $data[5], false);
							}							
							elseif($action){
								show_license_detail (false);
							}
								
							return true;
						}
						else{
							return;
						}
						
					} else if (strpos ( $result, '(101) Network is unreachable' ) !== FALSE) {
						unset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'jaccheking' )] );
						$_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'JAJOBBOARD_CHECKED' )] = true;
						JError::raiseWarning ( 1, JText::_ ( '(101) Network is unreachable' ) );
					} else {
						JError::raiseWarning ( 1, JText::_ ( 'Your license key is not accepted. Please contact <a href="http://support.joomlart.com/">JoomlArt</a> for further assistance.') );						
					}										
				}
		}
	}
	
	return;
}

/**
 * Enter description here...
 *
 */

function update_license_config($domains, $expired_date = 0, $type = 'Trial', $status = '', $create_date = 0, $date_show = '') {
	global $mainframe;
	
	$db = JFactory::getDBO ();
	$sql = "select * from #__ja_config where tab='license'";
	$db->setQuery ( $sql );
	$old_license = $db->loadObject ();
	$data = isset ( $old_license->data ) ? $old_license->data : '';
	$params = new JParameter ( $data );
	$domains = trim ( $domains );
	$ips = getRealIpAddr ();
	$base = $mainframe->getSiteUrl ();
	
	if ($domains)
		$params->set ( 'domains', $domains );
	
	if ($ips && $domains) {
		if ($params->get ( 'ips', '' ) && strpos ( $params->get ( 'ips', '' ), $ips ) === FALSE) {
			$ips = $params->get ( 'ips', '' ) . ', ' . $ips;
			$params->set ( 'ips', $ips );
		} elseif (! $params->get ( 'ips', '' )) {
			$params->set ( 'ips', $ips );
		}
	}
	if ($expired_date) {
		$params->set ( 'expired_date', $expired_date );
	} else {
		if (! $params->get ( 'expired_date' )) {
			$expired_date = strtotime ( date ( "Y-m-d" ) . " +30 days" );
			$params->set ( 'expired_date', $expired_date );
		} else {
			$expired_date = $params->get ( 'expired_date' );
		}
	}
	
	if ($create_date) {
		$params->set ( 'create_date', $create_date );
	} else {
		if (! $params->get ( 'create_date' )) {
			$create_date = time ();
			$params->set ( 'create_date', $create_date );
		} else {
			$create_date = $params->get ( 'create_date' );
		}
	}
	if ($date_show)
		$params->set ( 'date_show', $date_show );
	
	$email = trim ( JRequest::getVar ( 'email', '' ) );
	if ($email != '')
		$params->set ( 'email', $email );
	
	if ($type)
		$params->set ( 'type', $type );
	$lasted_check = time ();
	$params->set ( 'lasted_check', $lasted_check );
	$rebuilt_code = md5 ( trim ( $params->get ( 'domains' ) ) . trim ( $params->get ( 'ips' ) ) . trim ( $params->get ( 'expired_date' ) ) . trim ( $params->get ( 'lasted_check' ) ) . trim ( $params->get ( 'email' ) ) . trim ( $status ) . 'JA_LICENSE_JOB_BOARD' );
	$params->set ( 'code', $rebuilt_code );
	
	if ($status) {
		$params->set ( md5 ( 'paused' ), $status );
	} else {
		$params->set ( md5 ( 'paused' ), '' );
	}
	
	$data = $params->toString ();
	
	if ($old_license) {
		$sql = "Update #__ja_config SET data='$data' where tab='license'";
		$db->setQuery ( $sql );
		$db->query () or die ( $db->ErrorMsg () );
	} else {
		$sql = "Insert into #__ja_config (data, tab) Values('$data', 'license')";
		$db->setQuery ( $sql );
		$db->query () or die ( $db->ErrorMsg () );
	}
	
	$query = "select * from #__users where usertype='Super Administrator' LIMIT 1";
	$db->setQuery ( $query );
	$user = $db->loadObject ();
	$params_user = new JParameter ( $user->params );
	
	if (isset ( $params_user )) {
		$params_user->set ( md5 ( 'jachecked' ), 1 );
		$data = $params_user->toString ();
		$query = "Update #__users SET params='$data' where id='{$user->id}'";
		$db->setQuery ( $query );
		$db->query ();
	}
	$_SESSION [$_SERVER ['HTTP_HOST'] . 'UPDATE_DONE'] = TRUE;
	return;
}

/**
 * Enter description here...
 *
 * @param unknown_type $tab
 * @param unknown_type $key
 */
function update_key_config($tab, $key) {
	$db = JFactory::getDBO ();
	$sql = "select * from #__ja_config where tab='$tab'";
	$db->setQuery ( $sql );
	$result = $db->loadObject ();
	
	if ($result) {
		$sql = "Update #__ja_config SET data='$key' where tab='$tab'";
		$db->setQuery ( $sql );
		$db->query () or die ( $db->ErrorMsg () );
	} else {
		$sql = "Insert into #__ja_config (data, tab) Values('$key', '$tab')";
		$db->setQuery ( $sql );
		$db->query () or die ( $db->ErrorMsg () );
	}
}

/**
 * Enter description here...
 *
 * @return unknown
 */
function show_license_detail($show_full=true) {
	$db = JFactory::getDBO ();
	$sql = "select * from #__ja_config where tab='license'";
	$db->setQuery ( $sql );
	$old_license = $db->loadObject ();
	if (! $old_license || $old_license->data == '') {
		JError::raiseWarning ( 1, JText::_ ( 'Please choose method.' ) );
		return display_form_activate_step1 ();
	}
	$params = new JParameter ( $old_license->data );
	?>
	<!--  -->
	<?php	echo JText::_ ( 'Verification has successful.' );?>
	
	<?php if(!$show_full) return ;?>
	<br />
	<a href="index.php?option=com_jajobboard"><?php
		echo JText::_ ( 'Start checking out JA Job Board now' )?></a>
	<br />
	<br />
	
	<?php
		echo JText::_ ( 'License information' ) . ': <br/>'?>
		<?php
		echo JText::_ ( '- License for domain' )?>: <?php
		echo $params->get ( 'domains', '' )?><br />
	<?php
		echo JText::_ ( '- Duration' )?>: <?php
		echo JText::_ ( 'Lifetime' )?>
	<br />
	[
	<a href="http://joomlart.com/forums/forumdisplay.php?f=157"><?php
		echo JText::_ ( 'Support Forum' )?></a>
	] - [
	<a href="http://wiki.joomlart.com"><?php
		echo JText::_ ( 'User Guides' )?></a>
	]
	<?php
}

/**
 * Enter description here...
 *
 * @return unknown
 */
function show_trial_license_detail($registered=false, $create_date, $domains, $max_domains=2, $show_full=true) {
	$db = JFactory::getDBO ();
	$sql = "select * from #__ja_config where tab='license'";
	$db->setQuery ( $sql );
	$old_license = $db->loadObject ();
	if (! $old_license || $old_license->data == '') {
		JError::raiseWarning ( 1, JText::_ ( 'Please active code.' ) );
		return display_form_activate_step1 ();
	}
	
	$params = new JParameter ( $old_license->data );
	$left_days = floor ( ($params->get ( 'expired_date', '' ) - time ()) / (60 * 60 * 24) ) + 1;
	$this_domain = $params->get ( 'domains', '' );
	
	if ($left_days<0) {
		$msg = sprintf('<b>Your testing license has expired.</b><br/>You have already requested  testing license of JA Job Board Component on %s.<br/><a href="http://www.joomlart.com/member/signup.php?group=jajobboard">Buy a new license</a> for this domain.<br/>Need help? <a href="http://support.joomlart.com">Submit support ticket</a> or send an email to <a href="mailto:jobboard@joomlart.com">jobboard@joomlart.com</a>', date ( "Y-m-d", $params->get ( 'create_date' ) ));
		JError::raiseWarning ( 1, $msg );
	} elseif ($registered) {		
		$msg = sprintf('You have already submitted a testing license of JA Job Board Component for this domain on %s. Your license is now updated to the system.<br/><br/>If you need to extend your testing period for specific reason, please submit a <a href="http://support.joomlart.com">support ticket</a> or send an email to <a href="mailto:jobboard@joomlart.com">jobboard@joomlart.com</a>', date ( "Y-m-d", $params->get ( 'create_date' ) ));
		JError::raiseNotice ( 1, $msg );
	
	} else {
		echo sprintf('The domain <b>%s</b> is not matching with the domain <b>%s</b> under your license details.<br/>For testing / development purpose, you can have <b>%s days</b> to test on this domain.<br/>On <b>%s</b>, the license on this domain will be expired and you must move this site to the official domain. Each license will be granted up to <b>%s</b> testing domains.', $this_domain, $domains, $left_days, date('Y-m-d', $params->get ( 'expired_date', '' )), $max_domains) . '<br /><br />';
	}
	
	if(!$show_full) return ;
	?>


	<a href="index.php?option=com_jajobboard"><?php
		echo JText::_ ( 'Start checking out JA Job Board now' )?></a>
	<br />
	
	<?php
		echo JText::_ ( 'License information' ) . ': <br/>'?>
			<?php
		echo JText::_ ( '- License for domain' )?>: <?php
		echo $this_domain?><br />
	<?php
		echo JText::_ ( '- Valid until' )?>: [<?php
		echo date ( "Y-m-d", $params->get ( 'expired_date' ) )?>] (<?php
		echo $left_days?> <?php
		echo JText::_ ( 'days left' )?>)
	<br />
	[
	<a href="http://joomlart.com/forums/forumdisplay.php?f=157"><?php
		echo JText::_ ( 'Support Forum' )?></a>
	] - [
	<a href="http://wiki.joomlart.com"><?php
		echo JText::_ ( 'User Guides' )?></a>
	]
	<?php
}

/**
 * Enter description here...
 *
 */
function redirect_to_license_manager() {
	global $mainframe;
	if (isset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'checking' )] ))
		unset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'checking' )] );
	$_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'JAJOBBOARD_CHECKED' )] = 1;
	$_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'JAJOBBOARD_UNVALID_LICENSE' )] = 1;	
}

/**
 * Enter description here...
 *
 */
function show_status_msg() {
	global $jbconfig;
	
	$db = JFactory::getDBO ();
	$sql = "select data from #__ja_config where tab='license'";
	$db->setQuery ( $sql );
	$data = $db->loadResult ();
	
	if (! $data)
		return;
	
	$params = new JParameter ( $data );
	
	$domain = $_SERVER ['HTTP_HOST'];
	if (strtolower ( substr ( $domain, 0, 3 ) ) == 'www') {
		$domain = substr ( $domain, strpos ( $domain, '.' ) + 1 );
	}	
	
	$jbconfig ['license']->set ( 'd13c3f7baed576768b11a714ef4d90e2', $params->get ( 'd13c3f7baed576768b11a714ef4d90e2' ) );
	switch ($params->get ( 'd13c3f7baed576768b11a714ef4d90e2' )) {
		case $domain . md5 ( 'invalid_domain' ) :
			{
				JError::raiseWarning ( 1, JText::_ ( 'Your license key is not accepted. Please contact <a href="http://support.joomlart.com/">JoomlArt</a> for further assistance.') );
				return;
			}
			break;
		
		case $domain . md5 ( 'expired' ) :
			{
				JError::raiseWarning ( 1, JText::_ ( 'Your license has expired. Therefore the system will be disabled. Please contact <a href="http://support.joomlart.com/">JoomlArt</a> for further assistance.' ) );
				return;
			}
			break;
		
		case $domain . md5 ( 'invalid_key' ) :
			{
				JError::raiseWarning ( 1, JText::_ ( 'Your license key is not accepted. Please contact <a href="http://support.joomlart.com/">JoomlArt</a> for further assistance.' ) );
				return;
			}
			break;
		
		case $domain . md5 ( 'disabled_domain' ) :
			{
				JError::raiseWarning ( 1, JText::_ ( 'Your license key is disabled. Please contact <a href="http://support.joomlart.com/">JoomlArt</a> for further assistance.' ) );
				return;
			}
			break;
	}
}


/**
 * Enter description here...
 *
 * @return unknown
 */
function check_license_time() {
	global $mainframe;
	
	$plan_check = 3*24*60*60*1000;//20;
	
	$db = JFactory::getDBO ();
	$sql = "select * from #__ja_config where tab='license'";
	$db->setQuery ( $sql );
	$old_licenses = $db->loadObject ();
	if ($old_licenses){
		$params = new JParameter ( $old_licenses->data );
	}
	else $params = new JParameter('');
	
	$expired_date =  0;
	$lasted_check =  0;
		
	if (! $old_licenses || trim ( $old_licenses->data ) == '') {
		$query = "select * from #__users where usertype='Super Administrator' LIMIT 1";
		$db->setQuery ( $query );
		$user = $db->loadObject ();
		$params_user = new JParameter ( $user->params );
		if ($params_user->get ( '88093ac8bb60bc7ef2aa311aa31c2a91' )) {
			redirect_to_license_manager ();
			JError::raiseWarning ( 1, JText::_ ( 'Your license key is not accepted. Please contact' ) . ' <a href="http://joomlart.com">JoomlArt</a>' . JText::_ ( 'for further assistance' ) );
			return;
		}
	} else {
		$expired_date =  ( int )trim ( $params->get ( 'expired_date' ) );
		$ips = trim ( $params->get ( 'ips' ) );
		$domains =  trim ( $params->get ( 'domains' ) );
		$lasted_check =  ( int )trim ( $params->get ( 'lasted_check' ) );
		$code = trim($params->get ( 'code' ));
		
		$rebuilt_code = md5 ( $domains . $ips . $expired_date . $lasted_check . trim ( $params->get ( 'email' ) ) . trim ( $params->get ( md5 ( 'paused' ) ) ) . 'JA_LICENSE_JOB_BOARD' );
		if ($rebuilt_code != $code) {
			redirect_to_license_manager ();
			JError::raiseWarning ( 1, JText::_ ( 'Your license key is not accepted. Please contact' ) . ' <a href="http://joomlart.com">JoomlArt</a>' . JText::_ ( 'for further assistance' ) );
			return false;
		}
		$domain = $_SERVER ['HTTP_HOST'];
		if (strtolower ( substr ( $domain, 0, 3 ) ) == 'www') {
			$domain = substr ( $domain, strpos ( $domain, '.' ) + 1 );
		}
		$list_domains = str_replace ( ' ', '', $domains );
		$list_domains = explode ( ',', $list_domains );
		if (! in_array ( $domain, $list_domains )) {
			$plan_check = 0;
		}
	}
	/*-------------*/	
	if ( $expired_date) {
		$duration_checked = time () - ( int ) $lasted_check;
		
		if ($duration_checked < $plan_check) {
			if (isset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'cheking' )] ))
				unset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'cheking' )] );
			if (isset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'jaerrors' )] ))
				unset ( $_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'jaerrors' )] );
			return true;
		} else { /* Auto checking*/
			$sql = "select * from #__ja_config where tab ='key'";
			$db->setQuery ( $sql );
			$row = $db->loadObject ();
			if ($row) {
				if ($row->data != '') {
					if (! defined ( 'AUTO_CHECKING' )){
						define ( 'AUTO_CHECKING', true );
					}
					
					if (! verify_new_license_key ( $row->data, false )) {
						redirect_to_license_manager ();
					} 
					else{
						return true;
					}
				}
					
			}
			
		}
		
	
	}
	
	$_SESSION [md5 ( $_SERVER ['HTTP_HOST'] . 'cheking' )] = true;
	return false;

}

function getPageTitleFromMenu()
{
	$menus = &JSite::getMenu();
	$menu = $menus->getActive();
	$title = '';
	if (is_object( $menu ) ) {
		$menu_params = new JParameter( $menu->params );
		$title = $menu_params->get( 'page_title','');
	
	}
	return $title;
}

function getProfileFromUserIdList($user_id)
{
	$db = JFactory::getDBO ();
	$query = "SELECT company FROM #__ja_profiles WHERE user_id in (" . $user_id.')';
	$db->setQuery ( $query );
	return implode(', ',$db->loadResultArray());
}

function JB_Build_where(&$join_clause_table, &$join_clause_field, &$field_temp, &$where_clause, $_fieldListEdit, $filter_field_keys, $request, $search='', $subwhere=array()){
	$db = JFactory::getDBO ();
	
	if ($_fieldListEdit ) {
		foreach ( $_fieldListEdit as $field ) {
			
			$field_temp[] =  " a.{$field->field_name} as {$field->field_name}_tmp ";
			
			if($filter_field_keys && in_array($field->field_name, $filter_field_keys) && $request[$field->field_name] && @$request['option']=='com_jajobboard'){	/* field in filter list */
			
				/* Parse text */
				$filter_text = $request[$field->field_name];
				if(!is_array($filter_text)){
					$filter_text = explode(',', $request[$field->field_name]);
				}
				foreach ($filter_text as $k=>$value){
					$filter_text[$k] = $db->Quote ( $db->getEscaped ( $value, true ));
				}
				$filter_text = implode(',', $filter_text);
						
				/* Referent table */
				if ($field->is_referred > 0) {
					$alias = substr($field->referred_table, 3, 5);					
															
					if(!in_array($alias, array_keys($join_clause_table))){
						$join_clause_table[$alias] = "\n LEFT JOIN #__{$field->referred_table} as  $alias";
					}													
					
					// Check sub category
					$subCat = "";
					if ( JRequest::getVar("layout", "") != "filter_job_list" &&  (JRequest::getVar("location_id", "") != "" || JRequest::getVar("cat_id", "") != "") ){
						$subSQL = "SELECT name FROM #__{$field->referred_table} WHERE parent_id IN (SELECT id FROM #__{$field->referred_table} WHERE name LIKE ". $filter_text .") ";
						// echo $subSQL;						
						$db->setQuery ( $subSQL );					
						$reTemp = $db->loadResultArray();
						if( count($reTemp) ){
							$subCat = ", '".implode("', '", $reTemp)."'";
							$filter_text .= $subCat;
						}
						// echo $filter_text;
					}
					
					
					/* field type is 'RADIO', 'SELECT' */
					if( $field->field_type!='MSELECT' ){																					
						$temp = " ON $alias.{$field->referred_key} = a.{$field->field_name} "; 

						if(!isset($join_clause_field[$alias]) || $join_clause_field[$alias]!=$temp){
							$join_clause_field[$alias] = $temp;
						} 
						
						$where_clause[] = 	" ($alias.{$field->referred_key} IN ($filter_text) ".
											" OR $alias.{$field->referred_value} IN ($filter_text) )";
					}
					else{	/* field type is 'MSELECT' */
						$temp = " ON a.{$field->field_name} LIKE concat($alias.{$field->referred_key}, ',%') " .
														" OR a.{$field->field_name} LIKE concat('%,', $alias.{$field->referred_key}, ',%')".
														" OR a.{$field->field_name} LIKE concat('%,', $alias.{$field->referred_key})".
														" OR a.{$field->field_name} = $alias.{$field->referred_key}";
						
						if(!isset($join_clause_field[$alias]) || $join_clause_field[$alias]!=$temp){
							$join_clause_field[$alias] = $temp;
						} 
						
						$where_clause[] = 	" ($alias.{$field->referred_key} IN ($filter_text) ".
											" OR $alias.{$field->referred_value} IN ($filter_text) )";
												
					}
					
				}
				elseif (in_array ( $field->field_type, array ('RADIO', 'SELECT', 'MSELECT' ) )) {	/* Data is stored the ja_codes table */
					
					$alias = 'code';
					
					if(!in_array($alias, array_keys($join_clause_table))){
						$join_clause_table[$alias] = "\n JOIN #__ja_codes as $alias ";
					}	
					
					/* field type is 'RADIO', 'SELECT' */
					if( $field->field_type!='MSELECT' ){
						
						$where_clause[] = 	" a.{$field->field_name} in ( SELECT #__ja_codes.value FROM #__ja_codes WHERE  #__ja_codes.text IN ($filter_text) ) ";
					}
					else{	/* field type is 'MSELECT' */
												
						$where_clause[] = 	" a.{$field->field_name} in ( SELECT #__ja_codes.value FROM #__ja_codes WHERE  #__ja_codes.text IN ($filter_text) ) ";
					}
					
				}
				else{						
					
					if(is_array($request[$field->field_name])){
						$request[$field->field_name] = implode(',', $request[$field->field_name]);
					}
					
					$where_clause[] = 	" a.{$field->field_name}=" . $db->Quote ( $db->getEscaped ( $request[$field->field_name], true ));
				}
			
			}
			elseif( $search && $field->is_on_filter && !in_array ( $field->field_type, array ('RADIO', 'SELECT', 'MSELECT' ) )){
				if ($field->is_referred > 0) {
					$alias = substr($field->referred_table, 3, 5);					
															
					if(!in_array($alias, array_keys($join_clause_table))){
						$join_clause_table[$alias] = "\n LEFT JOIN #__{$field->referred_table} as  $alias";
					}					
					
					$temp = " ON $alias.{$field->referred_key} =a.{$field->field_name}";

					if(!isset($join_clause_field[$alias]) || $join_clause_field[$alias]!=$temp){
						$join_clause_field[$alias] = $temp;
					} 
					
					$subwhere [] .= " ($alias.$field->referred_key LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . 
										" OR $alias.{$field->referred_value} LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ).
									  ")";
				}
				else{
					$subwhere [] .= " (a.$field->field_name LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . ")";
				}
			}							
		
		}
		if($subwhere)	$where_clause [] = '(' . implode ( ' or ', $subwhere ) . ')';
	}
}



function JB_Admin_Build_where(&$join_clause_table, &$join_clause_field, &$field_temp, &$where_clause, $_fieldListEdit, $filter_field_keys, $request, $search='', $subwhere=array()){
	$db = JFactory::getDBO ();
	
	if ($_fieldListEdit ) {
		foreach ( $_fieldListEdit as $field ) {
			
			$field_temp[] =  " a.{$field->field_name} as {$field->field_name}_tmp ";
			
			if($filter_field_keys && in_array($field->field_name, $filter_field_keys) && $request[$field->field_name]){	/* field in filter list */
			
				/* Parse text */
				$filter_text = $request[$field->field_name];
				if(!is_array($filter_text)){
					$filter_text = explode(',', $request[$field->field_name]);
				}
				foreach ($filter_text as $k=>$value){
					$filter_text[$k] = $db->Quote ( $db->getEscaped ( $value, true ));
				}
				$filter_text = implode(',', $filter_text);
						
				/* Referent table */
				if ($field->is_referred > 0) {
					$alias = substr($field->referred_table, 3, 5);					
															
					if(!in_array($alias, array_keys($join_clause_table))){
						$join_clause_table[$alias] = "\n LEFT JOIN #__{$field->referred_table} as  $alias";
					}													
					
					/* field type is 'RADIO', 'SELECT' */
					if( $field->field_type!='MSELECT' ){	
																										
						$temp = " ON $alias.{$field->referred_key} =a.{$field->field_name}";

						if(!isset($join_clause_field[$alias]) || $join_clause_field[$alias]!=$temp){
							$join_clause_field[$alias] = $temp;
						} 
						
						
						$where_clause[] = 	"($alias.{$field->referred_key} IN ($filter_text) ".
											" OR $alias.{$field->referred_value} IN ($filter_text) )";
					}
					else{	/* field type is 'MSELECT' */
						$temp = " ON a.{$field->field_name} LIKE concat($alias.{$field->referred_key}, ',%') " .
														" OR a.{$field->field_name} LIKE concat('%,', $alias.{$field->referred_key}, ',%')".
														" OR a.{$field->field_name} LIKE concat('%,', $alias.{$field->referred_key})".
														" OR a.{$field->field_name} = $alias.{$field->referred_key}";

						if(!isset($join_clause_field[$alias]) || $join_clause_field[$alias]!=$temp){
							$join_clause_field[$alias] = $temp;
						} 
						
						$where_clause[] = 	" ($alias.{$field->referred_key} IN ($filter_text) ".
											" OR $alias.{$field->referred_value} IN ($filter_text) )";
					}
					
				}
				elseif (in_array ( $field->field_type, array ('RADIO', 'SELECT', 'MSELECT' ) )) {	/* Data is stored the ja_codes table */
					
					$alias = 'code';
					
					if(!in_array($alias, array_keys($join_clause_table))){
						$join_clause_table[$alias] = "\n JOIN #__ja_codes as $alias ";
					}	
					
					/* field type is 'RADIO', 'SELECT' */
					if( $field->field_type!='MSELECT' ){
						
						$temp = " ON  $alias.field_id='{$field->table_name}_{$field->field_name}'".
														" AND  a.{$field->field_name}=$alias.value";
						if(!isset($join_clause_field[$alias]) || $join_clause_field[$alias]!=$temp){
							$join_clause_field[$alias] = $temp;
						} 
						$where_clause[] = 	" $alias.value IN ($filter_text) ";
					}
					else{	/* field type is 'MSELECT' */
						$join_clause_field[$alias] = " ON  $alias.field_id='{$field->table_name}_{$field->field_name}'".
														" AND (". 
														" a.{$field->field_name} LIKE concat( $alias.value, ',%' )".
														" a.{$field->field_name} LIKE concat( '%,', $alias.value, ',%' )".
														" a.{$field->field_name} LIKE concat( '%,', $alias.value )".
														" AND a.{$field->field_name}=$alias.value";
						$where_clause[] = 	" $alias.value IN ($filter_text) ";
					}

					
				}
				else{						
					
					if(is_array($request[$field->field_name])){
						$request[$field->field_name] = implode(',', $request[$field->field_name]);
					}
					
					$where_clause[] = 	" a.{$field->field_name}=" . $db->Quote ( $db->getEscaped ( $request[$field->field_name], true ));
				}
			
			}
			elseif( $search && $field->is_on_filter && !in_array ( $field->field_type, array ('RADIO', 'SELECT', 'MSELECT' ) )){
				
				
				if ($field->is_referred > 0) {
					$alias = substr($field->referred_table, 3, 5);					
															
					if(!in_array($alias, array_keys($join_clause_table))){
						$join_clause_table[$alias] = "\n LEFT JOIN #__{$field->referred_table} as  $alias";
					}					
					
					$temp = " ON $alias.{$field->referred_key} =a.{$field->field_name}";
					if(!isset($join_clause_field[$alias]) || $join_clause_field[$alias]!=$temp){
						$join_clause_field[$alias] = $temp;
					} 
																			
					$subwhere [] .= " ($alias.$field->referred_key LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . 
										" OR $alias.{$field->referred_value} LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ).
									  ")";
				}
				else{
					$subwhere [] .= " (a.$field->field_name LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . ")";
				}
			}							
		
		}
		if($subwhere)	$where_clause [] = '(' . implode ( ' or ', $subwhere ) . ')';
	}
}

function check_field_exist($field_name, $table){
	$db = JFactory::getDBO ();
	
	if(!$field_name || !$table) return false;
	$query = "SELECT count(id) FROM #__ja_form_fields WHERE  `published`=1 AND `field_name`='$field_name' and `table_name`='$table'";
	$db->setQuery ( $query );
	return $db->loadResult ();
}

function checkField_inserted($tableName, $columnName)
{
	//Global variable, $db for database name, these variable are common in whole application so stored in a global variable, alternatively you can pass this as parameters of function.
	
	$jconfig = new JConfig();
	$databasename = $jconfig->db;
	
	//Getting table fields through mysql built in function, passing db name and table name	
	$tableFields = @mysql_list_fields($databasename, $jconfig->dbprefix.$tableName);
	if( !$tableFields )
		return 0;
	
	//loop to traverse tableFields result set
	for($i=0;$i<mysql_num_fields($tableFields);$i++){
		//Using mysql_field_name function to compare with column name passed. If they are same function returns 1
		
		if(mysql_field_name($tableFields, $i)==$columnName)
		return 1;
	} //end of loop
	return 0;
}

	function setPageTitle( $arrConfig, $jobs=null, $defaultTitle=null ){
  	    /* Set page title */    	
    	global $jbconfig;
  	    $config = new JConfig();
		$document = JFactory::getDocument();
		if( ! is_object($jobs) ){
		    $jobs = new stdClass();
		    $jobs->title      = $defaultTitle;
		    $jobs->job_detail = "";
		}
		if( !isset($jbconfig['seo']) ){
			$document->setTitle( $jobs->title );
			return false;
		}
		// Title
		$title = $jbconfig['seo']->get($arrConfig[0], $defaultTitle);		
		$document->setTitle( replaceContentDocument($title, $jobs) );
		// Keyword
		$keyword = $jbconfig['seo']->get($arrConfig[1], "{SITE_KEYWORDS}");
		$document->setMetaData('keywords', replaceContentDocument($keyword, $jobs) );
		// Description
		$description = $jbconfig['seo']->get($arrConfig[2], "{SITE_DESCRIPTION}");
		$document->setDescription( replaceContentDocument($description, $jobs) );
		return true;
  	}

  	function replaceContentDocument($define, $jobs){
  	    $config = new JConfig();
  	    
  	    $define = str_replace("{JOB_TITLE}", JText::_($jobs->title), $define);
  	    $define = str_replace("{PROFILE_TITLE}", JText::_($jobs->title), $define);
  	    $define = str_replace("{RESUME_TITLE}", JText::_($jobs->title), $define);
  	    $define = str_replace("{JOB_DESCRIPTION}", $jobs->job_detail, $define);
  	    $define = str_replace("{SITE_TITLE}", JText::_($config->sitename), $define);
  	    $define = str_replace("{SITE_DESCRIPTION}", $config->MetaDesc, $define);
  	    $define = str_replace("{SITE_KEYWORDS}", $config->MetaKeys, $define);
  	    
  	    return $define;
  	}
?>